Warning : This is content is getting old and may be out of date
Recently I encountered a cast that I found interesting. It was trying to convert an integer into an enumeration in a way I never met before. Let’s take this enumeration type :
And the following cast :
My first reaction was to wonder why converting an integer into a string to cast it into an enumeration just after when a simple direct cast is enough ?
I ask a workmate If I didn’t miss a thing and I was answered that Enum.Parse throws an exception if the val variable has a value that doesn’t fit in the enumeration (for example 2).
As I was not totally convinced I decided to create a little test :
With all of these tests I realized all the casts were working with a value of 2. No exception thrown. This means that the numerical value of res is 2 when the maximum value of the enumeration is 1 ! This feels like C.
Now what happens with the following test:
This time we have got an exception indicating that the value “Two” doesn’t exist in the enumeration, which is an expected behavior.
If we go back to the code that troubled me at the beginning of this post we realize the developer error was to think that Enum.Parse works the same way with strings than with strings containing an integer.
Therefore how can we be sure that the value we want to convert exists in the enumeration ?
We have many choices :
The first method only exists starting .NET 4 whereas the second exists in the previous framework versions too.
We learn everyday our favorite language :-)
Did you expect such a behavior ?