Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I assign null to value of Type "struct Nullable<T>" but not to my struct?

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?

like image 576
BennoDual Avatar asked Mar 07 '23 06:03

BennoDual


1 Answers

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.

like image 64
Marc Gravell Avatar answered Apr 07 '23 06:04

Marc Gravell