Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# value type initialized with null

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;
like image 499
mgamer Avatar asked Nov 24 '10 18:11

mgamer


1 Answers

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.)

like image 137
Jon Skeet Avatar answered Sep 19 '22 10:09

Jon Skeet