Home > View Post

How to test if a Type supports nulls

Given a particular System.Type, how can I tell whether it would support nulls? Sounds easy enough as we all know that Value Types can't be null (int, DateTime and all structs have default values) and Reference Types can be null (string, object and all classes). The System.Type class is also kind enough to provide an IsValueType property...

Assert.IsTrue(typeof(int).IsValueType); // ok :)
Assert.IsFalse(typeof(string).IsValueType); // also good :)

But then I ran into a small problem highlighted by one of my unit tests against an int? type (actually an instance of the generic type Nullable<T> known as a nullable type).

Assert.IsFalse(typeof(int?).IsValueType); // Fails!!

I had assumed that because nullable types can be null they're Value Types but closer inspection actually reveals that Nullable<T> is actually a struct. Try again:

public static void CanBeNull(Type type)
{
    return !type.IsValueType ||
        (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>));
}

Assert.IsTrue(CanBeNull(typeof(string))); //     :)
Assert.IsFalse(CanBeNull(typeof(int))); //         :)
Assert.IsTrue(CanBeNull(typeof(int?))); //     :D

Anything I've missed?

_______________
PS - I wasn't actually using unit tests to test System.Type's IsValueType as I do in the top two code snippets, but I think it's a nice way of making a point.

Tags: .NET

 
Josh Post By Josh Twist
2:37 AM
03 Nov 2006

» Next Post: The difference between Equals equals
« Previous Post: NullableExtender revisited

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.