Home All Groups Group Topic Archive Search About

Reflection and Nullable

Author
13 Jul 2006 4:00 PM
Joe Bloggs

Hi,

Can someone please kindly show me how to determine if a type (read
value
type) is Nullable.

MSDN has this KB:
How to: Identify a Nullable Type (C# Programming Guide)
http://msdn2.microsoft.com/en-us/library/ms366789.aspx

however, using their code snippet, I couldn't get it to work:

public class MyClass
{
public static void Main()
{
  Nullable<int> j = new Nullable<int>(20);
  Type type = j.GetType();
  if (type.IsGenericType && type.GetGenericTypeDefinition() ==
typeof(Nullable<>))
  {
     Console.WriteLine("j is Nullable");
  }
  else
     Console.WriteLine("j is NOT Nullable");

   Console.WriteLine("Type of j is {0}", j.GetType());
}
}

The Output I got is:

j is NOT Nullable
Type of j is System.Int32

thus, is there  no way to determine a nullable or an non-nullable value

types?

Thanks for your help in advanced.
Author
13 Jul 2006 6:13 PM
Barry Kelly
"Joe Bloggs" <es***@rocketmail.com> wrote:

> Can someone please kindly show me how to determine if a type (read
> value
> type) is Nullable.

I answered in your multipost in dotnet.general.

-- Barry

Are all your drivers up to date? click for free checkup

Author
13 Jul 2006 6:23 PM
Jon Skeet [C# MVP]
Joe Bloggs <es***@rocketmail.com> wrote:
> Can someone please kindly show me how to determine if a type (read
> value type) is Nullable.

Finding out if a type is nullable is fine, but you can't find out from
a value in the way you're doing. This is because calling GetType()
involves boxing the nullable value. Now, from the C# spec:

<quote>
A boxing conversion from a nullable type T? is processed as follows:

*      If the source value is null (HasValue property is false), the
result is a null reference of the target type.
*      Otherwise, the result is a reference to a boxed T produced by
unwrapping and boxing the source value.
</quote>

In other words, by the time you call GetType(), you're either calling
it on null (resulting in an exception) or on the boxed non-nullable
value type.

Now, do you actually need it from a Type object? If so, the test you
showed works fine. (Try it with typeof(Nullable<int>).)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Bookmark and Share