Is It Nullable ?

Sometimes, you may have a scenario whereby you need to know if a value is a value type (say 'int'), or a nullable type (say 'int?').

Common sense suggests that we should easily be able to detect wether a type is nullable or not, but if you have a try, you'll see there are no obvious answers, or many unobvious ones either.

The problem stems from the fact that if you query the type of a nullable instance it'll cause it to be boxed, and the boxing operation means that GetType() brings back the type of the underlying valuetype - not the nullable.

However, after a bit of head-scratching, I ended up with this utility class

public static class ValueTypeHelper
{
    public static bool IsNullable<T>(T t) { return false; }
    public static bool IsNullable<T>(T? t) where T : struct { return true; }
}

and here's the test

static void Main(string[] args)
{
    int a = 123;
    int? b = null;
    object c = new object();
    object d = null;
    int? e = 456;
    var f = (int?)789;
    bool result1 = ValueTypeHelper.IsNullable(a); // false
    bool result2 = ValueTypeHelper.IsNullable(b); // true
    bool result3 = ValueTypeHelper.IsNullable(c); // false
    bool result4 = ValueTypeHelper.IsNullable(d); // false
    bool result5 = ValueTypeHelper.IsNullable(e); // true
    bool result6 = ValueTypeHelper.IsNullable(f); // true

}

Dean

Comments (2) -

Kevin
Kevin
7/22/2011 4:53:23 AM #

I like your solution but wouldn't it be better to call your methods IsValueTypeNullable? The fact that c and d result in false are only correct if you're testing them as nullable value types. But if you need to know whether the instance (be it of int?, object, or some reference type) is null then c and d should return true.

Adding to your sample set, I tried this statement:  
    object j = e;
which resulted in false. Is that what you would expect/want?

eduardo
eduardo
10/26/2011 4:39:31 PM #

Hello, this post is very usefull for me, do you have a VB .NET version of IsNullable function?
Thanks

Pingbacks and trackbacks (2)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About the author

I am a senior .NET contract (freelance) software developer specialising in WPF and WinRT application development with C#, F#, C++. I mainly work in the Investment Bnking industry building performant and robust user interfaces for front office and middle office systems

RecentComments

Comment RSS

Month List