Sadiq
Sadiq

Reputation: 838

WHY Nullable<T>,struct, allows 'null'

Nullable is an struct. And i know structs cant be assigned 'null'. So how could we assign Nullable's object a null? What is the reason?

Upvotes: 3

Views: 513

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

It doesn't actually accept a value of null; it simply has syntactic sugar that allows it to act like it's null. The type actually looks a bit like this:

struct Nullable<T>
{
    private bool hasValue;
    private T value;
}

So when it's initialized hasValue == false, and value == default(T).

When you write code like

int? i = null;

The C# compiler is actually doing this behind the scenes:

Nullable<T> i = new Nullable<T>();

And similar checks are made when casting null to an int? at run-time as well.

Further Reading

Upvotes: 10

Related Questions