I have a class called Questions
(plural). In this class there is an enum called Question
(singular) which looks like this.
public e
One more way to do it:
Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);
It will result in:
Name: Role, Value: 2
Use:
Question question = Question.Role;
int value = Convert.ToInt32(question);
public enum Suit : int
{
Spades = 0,
Hearts = 1,
Clubs = 2,
Diamonds = 3
}
Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));
// From int
Console.WriteLine((Suit)1);
// From a number you can also
Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));
if (typeof(Suit).IsEnumDefined("Spades"))
{
var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
Console.Out.WriteLine("{0}", res);
}
It's easier than you think - an enum is already an int. It just needs to be reminded:
int y = (int)Question.Role;
Console.WriteLine(y); // Prints 2
Example:
public enum EmpNo
{
Raj = 1,
Rahul,
Priyanka
}
And in the code behind to get the enum value:
int setempNo = (int)EmpNo.Raj; // This will give setempNo = 1
or
int setempNo = (int)EmpNo.Rahul; // This will give setempNo = 2
Enums will increment by 1, and you can set the start value. If you don't set the start value it will be assigned as 0 initially.
I came up with this extension method that includes current language features. By using dynamic, I don't need to make this a generic method and specify the type which keeps the invocation simpler and consistent:
public static class EnumEx
{
public static dynamic Value(this Enum e)
{
switch (e.GetTypeCode())
{
case TypeCode.Byte:
{
return (byte) (IConvertible) e;
}
case TypeCode.Int16:
{
return (short) (IConvertible) e;
}
case TypeCode.Int32:
{
return (int) (IConvertible) e;
}
case TypeCode.Int64:
{
return (long) (IConvertible) e;
}
case TypeCode.UInt16:
{
return (ushort) (IConvertible) e;
}
case TypeCode.UInt32:
{
return (uint) (IConvertible) e;
}
case TypeCode.UInt64:
{
return (ulong) (IConvertible) e;
}
case TypeCode.SByte:
{
return (sbyte) (IConvertible) e;
}
}
return 0;
}