views:

374

answers:

7

when I declare an int as nullable

int? i=null;

Is i here become a reference type?

+17  A: 

No, a nullable is a struct. What is happening is that the nullable struct has two values.

  1. The value of the data type (int for int?, DateTime for DateTime? etc.).
  2. A boolean value which tells if the data type value has been set (HasValue is the property).

When you set the value of the data type the struct changes the HasValue to true.

What is a nullable

Kevin
You can't overload the `=` operator in C#. The boolean flag is set by the implicit conversion operator, not by the assignment operator.
sepp2k
oops thanks sepp2k.
Kevin
+2  A: 

No, the Nullable type is in fact a struct. The runtime will intelligently handle the setting of a null value for you, giving the appearance of a reference type, when it's not....

Matthew Abbott
+1  A: 

Nullable types cannot be reference types.

http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

Damien Dennehy
+6  A: 

From Nullable Types (C# Programming Guide):

Nullable types are instances of the System.Nullable struct.

and

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

So, no they're not reference types.

ChrisF
A: 

You shouldn't need to make a reference type a nullable type as you can pass null in its place.

devlife
A: 

Nullable types are neither value types nor reference types. They are more like value types, but have a few properties of reference types.

Naturally, nullable types may be set to null. Furthermore, a nullable type cannot satisfy a generic struct constraint. Also, when you box a nullable type with HasValue equal to false, you get a null pointer instead of a boxed nullable type (a similar situation exists with unboxing).

These properties make nullable types non-value types, but they sure aren't reference types either. They are their own special nullable-value type.

Stephen Cleary
A: 

So all declared but non-initialised value types are set by default to null using the System.Null namespace.

The nullable struct guarantees that all value types can return a recognisable null value (where all bits in the wordlength are zeroed out) if it is used before being initialised, and save many a headache with bugs I believe.

AlexW
Strings are treated differently and all null strings are instances of the System.String object.
AlexW