I was at a code review for one of the developers when I came across the following lines of code:
public void DoSomething(int value)The intention behind these lines was getting a value that was a value of the enum without having to expose the enum itself. In this case, the value was given by direct input from the user.
It might be obvious to some of you, but this code section has a few flaws. First of all, there is no check for the value and there is a conversion to the integer type for every case statement.
So I dug into the IL and found that one of these things was not even a problem: The code is compiled so that the values of the enum are translated to strongly typed integer values. This means that it doesn’t really matter, IL-wise, if you convert the value in the switch to the enum or each value to integer, it comes out the same.
What did bother me was the fact that this programmer didn’t check if the value sent to the method was even a valid value. This is done by using the Enum.IsDefined method and checks that the value passed is a defined value in the enum’s range of values.