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