rlesias
rlesias

Reputation: 6277

Overloading the = operator for nullable types?

The MSDN mentions that overloading the = operator is not possible.

How is it possible then for Nullable types to be assigned to null?

int? i = null;

Besides can I do it with my own generic types and how?

Upvotes: 1

Views: 646

Answers (4)

Servy
Servy

Reputation: 203814

There is special compiler support for the Nullable type.

It is impossible to create a user-defined implicit conversion to/from null. They built it into the language (and the runtime) rather than creating Nullable on top of the language, as so many BCL classes are made.

Interestingly this is not the only special support created for Nullable. When you box a Nullable<T> it doesn't actually box a Nullable object, ever. If HasValue is false, null is boxed, and if it's true, the underlying value is unwrapped and boxed. It would be impossible to do this for your own type.

Upvotes: 1

Chris
Chris

Reputation: 8656

Essentially what Tim's comment (Edit: And now answer =D) says - There's an implicit conversion from the null literal, rather than an overload of the assignment operator.

From the C# language spec (I was looking at Version 5.0) - Section "6.1.5 Null literal conversions":

An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460058

It's the implicit-conversion not the assignment-operator that allows to assign null: http://msdn.microsoft.com/en-us/library/ms131346(v=vs.110).aspx

If the value parameter is not null, the Value property of the new Nullable<T> value is initialized to the value parameter and the HasValue property is initialized to true. If the value parameter is null, the Value property of the new Nullable<T> value is initialized to the default value, which is the value that is all binary zeroes, and the HasValue property is initialized to false.

Upvotes: 2

Jay
Jay

Reputation: 10108

Nullable types are instances of the struct

System.Nullable<T>.

The type that can be specified or made nullable is specified as the generic type of nullable (T).

More info here...http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

In your example, you're not actually setting an int to null, rather setting the value on the struct which encapsulates it to null.

Upvotes: 1

Related Questions