Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if Type instance is a nullable enum in C#

Tags:

c#

enums

nullable

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? 
like image 549
adrin Avatar asked Apr 27 '10 16:04

adrin


People also ask

Is nullable enum?

Enum types cannot be nullable.

How can you tell if an enum is type?

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.

Can enum properties null?

“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).

How do you check if a property is nullable?

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.


2 Answers

public static bool IsNullableEnum(this Type t) {     Type u = Nullable.GetUnderlyingType(t);     return (u != null) && u.IsEnum; } 
like image 190
LukeH Avatar answered Oct 01 '22 02:10

LukeH


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; } 
like image 34
Jon Skeet Avatar answered Oct 01 '22 01:10

Jon Skeet