what is the best way to check if a certain Type is nullable or not.
some suggested codes out there are unable to test other Type especially string.
what is the best way to check if a certain Type is nullable or not.
some suggested codes out there are unable to test other Type especially string.
!certainType.IsValueType || Nullable.GetUnderlyingType(certainType) != null
the simplest way to do it:
public static bool IsNullable(this Type type)
{
if (type.IsValueType) return Activator.CreateInstance(type) == null;
return true;
}
these are my unit tests and all passed
IsNullable_String_ShouldReturn_True
IsNullable_Boolean_ShouldReturn_False
IsNullable_Enum_ShouldReturn_Fasle
IsNullable_Nullable_ShouldReturn_True
IsNullable_Class_ShouldReturn_True
IsNullable_Decimal_ShouldReturn_False
IsNullable_Byte_ShouldReturn_False
IsNullable_KeyValuePair_ShouldReturn_False
actual unit tests
[TestMethod]
public void IsNullable_String_ShouldReturn_True()
{
var typ = typeof(string);
var result = typ.IsNullable();
Assert.IsTrue(result);
}
[TestMethod]
public void IsNullable_Boolean_ShouldReturn_False()
{
var typ = typeof(bool);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_Enum_ShouldReturn_Fasle()
{
var typ = typeof(System.GenericUriParserOptions);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_Nullable_ShouldReturn_True()
{
var typ = typeof(Nullable<bool>);
var result = typ.IsNullable();
Assert.IsTrue(result);
}
[TestMethod]
public void IsNullable_Class_ShouldReturn_True()
{
var typ = typeof(TestPerson);
var result = typ.IsNullable();
Assert.IsTrue(result);
}
[TestMethod]
public void IsNullable_Decimal_ShouldReturn_False()
{
var typ = typeof(decimal);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_Byte_ShouldReturn_False()
{
var typ = typeof(byte);
var result = typ.IsNullable();
Assert.IsFalse(result);
}
[TestMethod]
public void IsNullable_KeyValuePair_ShouldReturn_False()
{
var typ = typeof(KeyValuePair<string, string>);
var result = typ.IsNullable();
Assert.IsFalse(result);
}