Reflection and Nullable in .Net 2.0

J

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

Barry Kelly

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

If you have the value in a variable of type object, you cannot. See
below for more details.
MSDN has this KB:
How to: Identify a Nullable Type (C# Programming Guide)
http://msdn2.microsoft.com/en-us/library/ms366789.aspx

The documentation on this page reads:

"Calling GetType on a Nullable type causes a boxing operation to be
performed when the type is implicitly converted to Object. Therefore
GetType always returns a Type object that represents the underlying
type, not the Nullable type."

Thus, the behaviour you're getting is as documented.
Nullable<int> j = new Nullable<int>(20);
Type type = j.GetType();

Nullable<T> doesn't override GetType(), so this method call ends up
boxing j. The way boxing nullable types works on the CLR is that null
values get turned into null references, while non-null inner values get
boxed into the inner type.

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

It is impossible to get a boxed nullable value in a variable of type
object. They do not occur. The boxed nullable value is either null or of
the inner type. Casting back to a nullable type performs the appropriate
null check automatically.

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top