3

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?

Sadiq
  • 786
  • 1
  • 10
  • 35
  • 1
    possible duplicate of [Why Nullable is a struct?](http://stackoverflow.com/questions/4272101/why-nullablet-is-a-struct) – V4Vendetta Apr 04 '13 at 12:10
  • 1
    @ Nolonar: Why it's done? I mean how could a struct object be assigned null? Its not possible for struct object to be assigned null. And Nullable itself is an struct. – Sadiq Apr 04 '13 at 12:12
  • The rules by which *you* have to play are not necessarily the rules by which the compiler and the CLR can play. – Damien_The_Unbeliever Apr 04 '13 at 12:15
  • @Sadiq you may also read this http://stackoverflow.com/a/13980357/570150 – V4Vendetta Apr 04 '13 at 12:19
  • @ Damien: You mean it is handeled at CLR level?? – Sadiq Apr 04 '13 at 12:20
  • 1
    No, more, as per p.s.w.g's answer, magic can happen when an apparent assignment of `null` to such a variable occurs - magic that you're not able to write in C# for your own classes. – Damien_The_Unbeliever Apr 04 '13 at 12:25

1 Answers1

10

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

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • I think he's wondering why id `DateTime? test = null` possible. – MarcinJuraszek Apr 04 '13 at 12:11
  • @ MarcinJuraszek: Yes.. that's what i mean. Or may be because Nullable overloads operator. Like == operator?? Dont know for sure. – Sadiq Apr 04 '13 at 12:19
  • 1
    @Sadiq It does override the `Equals` method. But `int? test = null` is actually more of a compiler trick. I've included a link to more detailed information in my answer. – p.s.w.g Apr 04 '13 at 12:26