I know the mechanism for Nullable Value Types. However, I am interested in the following:
The Nullable Value Types are working with the struct (from https://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e)
public struct Nullable<T> where T : struct {
public Nullable(T value) {
/* ... */
}
public bool HasValue {get;}
public T Value {get;}
}
I can use this like
Nullable<int> i = null;
Now, I create my own Nullable-Struct the same way:
public struct MyNullable<T> where T : struct {
public MyNullable(T value) {
/* ... */
}
public bool HasValue {get;}
public T Value {get;}
}
Why can I not do
MyNullable<int> i = null;
now?
I know, that values of struct cannot be null - but why can a value of the struct Nullable be null? Where is the mechanism which allows this?
Where is the mechanism which allows this?
In the C# compiler itself. Nullable<T>
is a special type with lots of extra rules, including how null
is handled (comparison and assignment), and how operators are handled (see: "lifted operators").
There is also support in the runtime for Nullable<T>
, for special "boxing" rules.
You cannot emulate Nullable<T>
in your own code, because of these special rules that you can't express.
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