Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Type check for enum instance base class?

Tags:

c#

enums

I have an enum type which derives from byte. In my common library, at some point there is a cast of an enum parameter to int. The problem is when my byte derived enum gets to that method in the common library, the cast to int fails and raises an exception.

Is there a way to type check an enum's base class so I can do the Int cast only for int based enums?

Here are two sample enums:

enum DaysByte : byte { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };
enum DaysInt  : int  { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri }; 
like image 652
Uri Abramson Avatar asked Oct 02 '14 13:10

Uri Abramson


1 Answers

You can use Enum.GetUnderlyingType method

Enum.GetUnderlyingType(typeof(YourEnum)) == typeof(int)

// or via enum value
Enum.GetUnderlyingType(yourEnumValue.GetType()) == typeof(int)
like image 102
Selman Genç Avatar answered Oct 06 '22 01:10

Selman Genç