Are nullable types reference types?
Asked Answered
P

6

150

When I declare an int as nullable

int? i=null;

Does i here become a reference type?

Playlet answered 30/6, 2010 at 12:22 Comment(0)
K
153

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 HasValue to true.

Nullable types (C# Programming Guide)

Kartis answered 30/6, 2010 at 12:23 Comment(1)
So, that means shallow cloning (with object.MemberwiseClone()) a nullable will result in a new "instance", right?Rosalvarosalyn
Z
27

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.

Zaffer answered 30/6, 2010 at 12:25 Comment(0)
C
18

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.

Cruiserweight answered 30/6, 2010 at 13:13 Comment(2)
As far as the type reflection API goes... typeof(int?).IsValueType equals true.Retro
@Gyromite: Yes, because Nullable<T> is a struct.Cruiserweight
C
6

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....

Christianize answered 30/6, 2010 at 12:24 Comment(1)
I'd query 'intelligently handle', rather subjective. Personally I find the behaviour confusing and often annoying.V1
L
1

Nullable types cannot be reference types.

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

Lundeen answered 30/6, 2010 at 12:25 Comment(0)
S
1

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

Spirula answered 30/6, 2010 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.