Beware of Enum.TryParse

What do you think Enum.TryParse will return when running this code?

public enum ContactMethod
{
   Unknown = 0,
   Email = 1,
   Phone = 2
}

var result = Enum.TryParse("10", out ContactMethod contactMethod);

"It will return false of course, 10 is not a valid value!!"

Wrong.
It will return true. And even worse, the output variable contactMethod will have the value of...10!

Don't believe me? See it for yourself (dotnetfiddle)

Now, imagine that some developer wrote the following program:

public class Program
{
	public static void Main(string args[])
	{
		var result = Enum.TryParse(args[0], out NukeStatus nukeStatus);
		FireNuke((int)nukeStatus);
	}
	
	public static void FireNuke(int status)
    {
	    if(status == 0)
	    {
	       return;
	    }
	
	    if(status > 0 && status <= 10)
	    {
	       Console.WriteLine("TEST FIRING");
           TestFire();
	    }
	
	    if(status >= 15)
	    {
	       Console.WriteLine("NUKE EM ALL!");
           NukeEmAll();
	    }
    }
}

public enum NukeStatus
{
   Idle = 0,
   TestFireOneMissile = 5,
   TestFireAllMissiles = 10,
   FireOneMissile = 15,
   FireAllMissiles = 20
}

Now imagine that someone with fat fingers should do a test run and slips on the keyboard, so instead of passing in 10, 100 will be passed in instead.

dotnet run TrumpNukeProgram 100

BOOM

Now, I know that my example is really stupid and the code is really bad, but still, it could happen!

What to use instead of Enum.TryParse then?

Note, this is only a problem when you try to pass in numeric values to TryParse.
If you want to be sure that your (int)value really exists in the Enum, you could use Enum.IsDefined instead.
Something like this:

var nukeStatusAsString = "100";
var myNukeStatus = int.Parse(nukeStatusAsString); // Yeah yeah, error checking I know.
var isDefined = Enum.IsDefined(typeof(NukeStatus), myNukeStatus);
if (!isDefined)
{
    return NukeStatus.Idle;
}
return (NukeStatus)myNukeStatus;

You can read more about this here (Stackoverflow) and here (Microsoft).

Share this