Did you know?

Did you know that in C# you can cast any number to any enum????
 
Look at the example:
 
public enum EnmYesNo
{
Yes = 1,
No = 2
}
 
int temp = 0;
EnmYesNo yesNo = (EnmYesNo)temp; // No error will shown
MessageBox.Show(yesNo.ToString()); // Will show ‘0’
 
temp = 154842;

EnmYesNo yesNo = (EnmYesNo)temp; // No error will shown
MessageBox.Show(yesNo.ToString()); // Will show ‘154842’
 
 
WOW!!!! I didn’t know about that, so the solution:
 
public static T ConvertEnum<T>(int t)
{
  if (Enum.IsDefined(typeof(T), t))
    return (T)Enum.Parse(typeof(T), t.ToString());
  else
    throw new Exception("Undefined Enum");
}
 
temp = 154842;

EnmYesNo yesNo = ConvertEnum<EnmYesNo>(temp); // An Exception will show up
MessageBox.Show(yesNo.ToString()); // unreachable code 🙂
 
Sadjad Bahmanpour
 

3 thoughts on “Did you know?”

  1. Dude, I don’t know what are you doing that you face such problems but it was good to know this. Thanks for sharing 🙂

  2. WOOOOOOOHOOOOOOOOOOOOO! Actually I knew this one 😀 (I’m so glad that I knew something that you didn’t!!! :p – Just kidding)Our policy here is to always check and throw in public methods, which receive enum parameters, for private and internal methods, you shouldn’t really care.You’re making it a little bit expensive here. For instance Enum.IsDefined does a lot of type checking, that depending on your scenario you might not need it. Also if all you want is to convert an integer to an enum, you won’t need the Enum.Parse. I would suggest to load all the values into a static hash set or something like that, and then just check if the value is present in the cache.

  3. Hey did you remove all the spam comments? Last time I came here, it was full of those spams, and it made me so frustrated, that I went and reported the guy right away. I’m wondering if that’s what has caused the comments to be gone now! :)On a side note, I was just reading about new Features of C# 2010, and I found some of them really interesting. Along them were a few things that I’ve been waiting for quite some time to have them, and I guess same is true with you. For instance the dynamic type, and covariance, and contravariance, and in particular the two latter ones.

Leave a Reply