Alpha
Alpha

Reputation: 7868

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!

Upvotes: 4

Views: 981

Answers (4)

Reed Copsey
Reed Copsey

Reputation: 564861

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.

Upvotes: 10

payo
payo

Reputation: 4561

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.

Upvotes: 5

jorgehmv
jorgehmv

Reputation: 3713

According to this page Operator overloading

Note that the assignment operator itself (=) cannot be overloaded.

You can define an implicit operator

Upvotes: 1

Yogu
Yogu

Reputation: 9455

Not the assignment operator is overloaded, but the class Nullable<T> specifies an implicit conversion operator which is able to convert T into Nullable<T>.

You can easily add this functionality to your class:

class MyInteger {
  private int value;

  public MyInteger(int value) { this.value = value; }

  public static implicit operator MyInteger(int value) {
    return new MyInteger(value);
  }
}

And then use the operator in the same way:

MyInteger obj = 123;

Upvotes: 3

Related Questions