开发者

Looking for a more elegant way to check for nullable value types

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

int? i = null;
bool isNullable = i.GetType().ToString().Contains开发者_如何学C("System.Nullable");

Is there a more elegant way to do this?


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.


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

This is how Microsoft recommends you Identify Nullable Types


int? i;
bool isNullable = i is Nullable;

Edit: Nevermind, this doesn't work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜