Reputation: 1007
If you declare an enum in C#, the default type is automatically int.
So then why in a case statement or other instances when using the enum do you have to explicitly recast in order to use the values? What's the point of having an underlying type if you have to explicitely case or am I just doing something wrong here?
private enum MyEnum
{
Value1,
Value2,
Value3
}
switch (somevalue)
{
case (int)MyEnum.Value1:
someothervar = "ss";
break;
case (int)MyEnum.Value2:
someothervar = "yy";
break;
case (int)MyEnum.Value3:
someothervar = "gg";
break;
}
Upvotes: 8
Views: 8271
Reputation: 1661
As others have said:
Upvotes: 1
Reputation: 64148
Obviously somevalue is an integer rather than explicitly typed as your enum. You should keep in mind that the underlying value of an enum is just the "storage type" and is not implicitly interchangeable. However, you can easily use the cast operator to make your code simple and "more" type safe:
private enum MyEnum { Value1, Value2, Value3 }
switch ((MyEnum)somevalue)
{
case MyEnum.Value1:
someothervar = "ss";
break;
case MyEnum.Value2:
someothervar = "yy";
break;
case MyEnum.Value3:
someothervar = "gg";
break;
default:
throw new NotSupportedException();
}
Eventually you would like a design where you did not have to convert from an integer to an enum, but often times when reading from disk or DB this is not the case.
Upvotes: 4
Reputation: 755587
What is the type of somevalue? If the type is MyEnum casting is un-necessary and should work without error.
If the type is int then yes you will have to cast up to a MyEnum in order to properly switch / case. But you can make this a bit simpler by casting the value instead of every case statement. For example
switch( (MyEnum)somevalue ) {
case MyEnum.Value1: ...
}
Upvotes: 15
Reputation: 300837
If somevalue
is of type MyEnum
, you don't have to cast to an int
.
public enum Color
{
Red,
Blue,
Green
}
class Program
{
static void Main(string[] args)
{
Color color = Color.Red;
switch (color)
{
case Color.Red:
break;
case Color.Blue:
break;
case Color.Green:
break;
}
}
}
Upvotes: 2