In C# 3.0 you can assign null to int? type (in CLR int? is a struct):
int? a = null;
but when you define a custom struct:
struct MyStruct
{
}
there's an error during the compilation of this code:
MyStruct a = null;
The error is as follows:
Cannot convert null to 'Example.MyStruct' because it is a non-nullable value type
While int? is a struct in CLR it is somehow counterintuitive that we can assign null to it. I suppose that null is implicitly casted or boxed to a certian int? value that represents the null value. How is it done precisely? How can I extend MyStruct in such a way that it would be possible to execute the line:
MyStruct a = null;
It's because int?
is actually shorthand Nullable<int>
. You can do the same thing for your type too:
MyStruct? a = null;
null
can only be implicitly converted to a nullable type, which means any reference type or any nullable value type - where the latter means Nullable<T>
for some T
.
Note that this ability to conver from null
is really a language feature - the compiler is converting this:
int? a = null;
into
int? a = new int?();
They mean the same thing - basically a "null" value for a nullable value type is a value where HasValue
is false, which it will be by default. It's not the same as a null reference - although boxing a null value like that will result in a null reference.
(This is one example of a feature which crosses language, library and CLR boundaries. The library part is quite simple, the CLR part is only to do with boxing and unboxing - but there's quite a lot in terms of lifted operators etc in the language.)
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