When I program in Java, I make all nullability explicit; that is, an instance of Foo is assumed to be non-null, and if I want it to be null, I use a @Nullable
annotation (or better, Optional<Foo>
). But C# doesn't natively support annotations, and Nullable<> is only for value types.
But what if I did something like this?
struct Value<T> where T : class {
T value;
}
And then use Value<Foo>?
as the type for a field. What impact would this have on performance/memory, and is there something that makes this a very bad idea?
MiscUtil.NonNullable<T>
, available at jonskeet.uk/csharp/miscutil . I would encourage you to read the source code (including the comments) withinNonNullable.cs
; it handles numerous scenarios that you may not have considered.