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
}
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.
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.
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.
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