Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Enum type from value

Tags:

c#

enums

public enum WeekDays { Sun = 1, Mon = 2, Tue=3, Wed=4, Thu=5, Fri=6, Sat=7 }

I have this enum, I have the value of the enum. what I want to do is by passing value get the type that I want to pass this to below function. I can do this by switch case any better ways??

for Example : value is 6 then Weekdays.Fri as a type should be passed to the below function.

  public void CreateNew(WeekDays days)
  {
   //Some logic
  }
like image 417
ankur Avatar asked Jan 03 '13 11:01

ankur


People also ask

How to get value enum C#?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

When to use enum C#?

In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays. Monday is more readable then number 0 when referring to the day in a week.


1 Answers

All you need to do is cast the value.

CreateNew((WeekDays)6);

enum values are essentially just typed integers, so you can freely cast both ways between enum and integral types. It's even possible to cast an integer value that doesn't exist in the enum into that type with no problem, so if you want to avoid that, remember to add validation that checks that the value exists before casting.

like image 93
Matti Virkkunen Avatar answered Nov 15 '22 11:11

Matti Virkkunen