Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active March 24, 2024 04:38
Show Gist options
  • Save relyky/62963953866a0113bb546211a4281107 to your computer and use it in GitHub Desktop.
Save relyky/62963953866a0113bb546211a4281107 to your computer and use it in GitHub Desktop.
c#, is nullable, IsNullable, How to check if an object is nullable?
///
/// How to check if an object is nullable?
/// ref → http://stackoverflow.com/questions/374651/how-to-check-if-an-object-is-nullable
///
static bool IsNullable<T>(T obj)
{
if (obj == null) return true; // obvious
Type type = typeof(T);
if (!type.IsValueType) return true; // ref-type
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
return false; // value-type
}
static bool IsNullable<T>()
{
Type type = typeof(T);
if (!type.IsValueType) return true; // ref-type
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
return false; // value-type
}
//# Testing
Decimal C = 9;
Decimal? D = 9;
bool b1 = IsNullable(C); // false
bool b2 = IsNullable(D); // ture
bool b3 = IsNullable<Decimal>(); // false
bool b4 = IsNullable<Decimal?>(); // ture