views:

117

answers:

3

To check if a value type is nullable I'm currently doing something like this:

int? i = null;
bool isNullable = i.GetType().ToString().Contains("System.Nullable");

Is there a more elegant way to do this?

+7  A: 
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
  // it is a nullable type
}

This is how Microsoft recommends you Identify Nullable Types

w69rdy
Wow - that's a strange recommendation for Microsoft to make given that there's a built-in method to do this. (See my answer.)
Jon Skeet
Yeah it seems a bit more long winded. Looking at yours, could it be that it returns null if its not a nullable type and that although you can use it to check if a type is nullable it's not strictly meant for that purpose? (although it is quicker!)
w69rdy
@w69wrdy: Well it gives more information than you require - but it gives you all the information you *do* require and in a simpler way. It's *very slightly* less efficient in the case where it's a nullable type, as it'll also get the generic type arguments... but I'd go for readability and simplicity any day.
Jon Skeet
A: 
int? i;
bool isNullable = i is Nullable;

Edit: Nevermind, this doesn't work.

TheSean
Did you try this?
Jon Skeet
This doesn't seem to work, I get this compiler warning:The given expression is never of the provided ('System.Nullable') type
RobSullivan
@RobSullivan: Yes, it's checking for compatibility with the System.Nullable static class... which is never going to work. I've been assuming you've got an instance of `Type` btw - if you've got an *actual variable* with a concrete type then you already know the result...
Jon Skeet
opps sorry, thought this worked!
TheSean
Don't forget that you can delete wrong answers.
Georg Fritzsche
+12  A: 

You can use Nullable.GetUnderlyingType(Type) - that will return null if it's not a nullable type to start with, or the underlying value type otherwise:

if (Nullable.GetUnderlyingType(t) != null)
{
    // Yup, t is a nullable value type
}

Note that this uses the Nullable static class, rather than the Nullable<T> structure.

Jon Skeet
+1 Id probably go with this one since its a lot cleaner, plus looking at Reflector, this also checks to make sure the type is not a generic type definition.
SwDevMan81