I always thought that the nullable types of the .NET framework where nothing but a nice construct that the framework gave us, but wasn't anything new added to the language itself.
That is, until today, for purposes of a demonstration, I tried to create my own Nullable struct.
I get everything I need, except the capability of doing this:
var myInt = new Nullable<int>(1);
myInt = 1;
The problem is the second statement, as I cannot, by any means, overload the assignment operator.
My question is: Is this a special case in the language where the assignment operator has an overload? If not, how would you approach making that previous example work?
Thanks!
The assignment is question is handled using an implicit operator declared as:
public static implicit operator Nullable<T> (T value)
This is handled without any language-specific features.
The main change to the langauge for nullable support is the ability to write this as:
int? myInt = 1;
You could implement this in your type via:
public static implicit operator Nullable<T> (T value)
{
return new Nullable<T>(value);
}
That being sad, there is a lot of features related to Nullable<T>
the C# language and CLR does that can't be duplicated in your code.
Ditto on the other answers, but note that Nullable<T>
does do some magic as well.
Quoting from that answer by Lippert
C# automatically lifts operators to nullable. There's no way to say "automatically lift operators to MyNullable". You can get pretty close by writing your own user-defined operators though.
C# has special rules for null literals -- you can assign them to nullable variables, and compare them to nullable values, and the compiler generates special code for them.
The boxing semantics of nullables are deeply weird and baked into the runtime. There is no way to emulate them.
Nullable semantics for the is, as and coalescing operators are baked in to the language.
Nullables do not satisfy the struct constraint. There is no way to emulate that.
And so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With