Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable is not a ValueType

Tags:

c#

nullable

If you look at the documentation for the .NET Nullable, you'll see:

   struct Nullable<T>

Note that it's a struct, not a class.

It seems a struct Nullable<T> is not a ValueType, which is very unexpected. The following code prints False:

   Type nullableType = typeof(Nullable<int>);
   Console.WriteLine(nullableType is ValueType);

If you look at the generated IL you'll see that that compiler determined nullableType to be a ValueType at compile time. But how can it be a ValueType if it's a struct? All structs are ValueTypes, right? Obviously, it has something to do with the generic.

What am I missing here? Is there something in the language spec about this?

Thanks.

like image 344
Tom Baxter Avatar asked Jul 13 '11 03:07

Tom Baxter


2 Answers

You are testing if System.Type is a value type. It is not. Rewrite it like this:

Nullable<int> test = 42;
Console.WriteLine(test is ValueType);
like image 194
Hans Passant Avatar answered Sep 30 '22 20:09

Hans Passant


It is a value type, try it this way:

Type nullableType = typeof(Nullable<int>);
Console.WriteLine(nullableType.IsValueType);

That should return true. Hope that helps.

like image 33
rsbarro Avatar answered Sep 30 '22 20:09

rsbarro