Pregunta

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?

¿Fue útil?

Solución 3

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.

Otros consejos

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.

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.

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top