How do i check if a Type is a nullable enum in C# something like
Type t = GetMyType(); bool isEnum = t.IsEnum; //Type member bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?
Enum types cannot be nullable.
In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false. It is a read-only property.
“c# enum value null” Code Answer An enum is a "value" type in C# (means the the enum is stored as whatever value it is, not as a reference to a place in memory where the value itself is stored). You can't set value types to null (since null is used for reference types only).
Checking if PropertyType is nullable is useable when adding column to `DataTable` object. If column to be added is nullable type, we need to explicitly set it. To check if PropertyType is nullable, we can use `System. Nullable.
public static bool IsNullableEnum(this Type t) { Type u = Nullable.GetUnderlyingType(t); return (u != null) && u.IsEnum; }
EDIT: I'm going to leave this answer up as it will work, and it demonstrates a few calls that readers may not otherwise know about. However, Luke's answer is definitely nicer - go upvote it :)
You can do:
public static bool IsNullableEnum(this Type t) { return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>) && t.GetGenericArguments()[0].IsEnum; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With