Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable types and assignment operator

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!

like image 965
Alpha Avatar asked Dec 02 '22 00:12

Alpha


2 Answers

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.

like image 152
Reed Copsey Avatar answered Dec 13 '22 13:12

Reed Copsey


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.

like image 38
payo Avatar answered Dec 13 '22 12:12

payo