typeof check for nullability

  • Thread starter Thread starter Andrew Robinson
  • Start date Start date
A

Andrew Robinson

I am guessing there is a simple solution but given a type T, how can I check
for nullability?

how can I accomplish the following?

bool nullable = typeof(int).IsNullable; // false
bool nullable = typeof(int?).IsNullable; // true
bool nullable = typeof(string).IsNullable; // true

Thanks for any help.
 
Andrew Robinson said:
I am guessing there is a simple solution but given a type T, how can I check
for nullability?

how can I accomplish the following?

bool nullable = typeof(int).IsNullable; // false
bool nullable = typeof(int?).IsNullable; // true
bool nullable = typeof(string).IsNullable; // true

using System;

class Test
{
static void Main()
{
Console.WriteLine (IsNullable(typeof(int)));
Console.WriteLine (IsNullable(typeof(int?)));
Console.WriteLine (IsNullable(typeof(string)));
}

static bool IsNullable (Type t)
{
return !t.IsValueType ||
(t.IsGenericType &&
t.GetGenericTypeDefinition()==typeof(Nullable<>));
}
}
 
Thanks,

--

Andrew Robinson


Jon Skeet said:
using System;

class Test
{
static void Main()
{
Console.WriteLine (IsNullable(typeof(int)));
Console.WriteLine (IsNullable(typeof(int?)));
Console.WriteLine (IsNullable(typeof(string)));
}

static bool IsNullable (Type t)
{
return !t.IsValueType ||
(t.IsGenericType &&
t.GetGenericTypeDefinition()==typeof(Nullable<>));
}
}
 
Back
Top