Beware of pits in enum parse


Beware of pits in enum parse


Recently, when using enumeration, I stepped on a small pit to share. The main reason is that enumeration may encounter problems when it is converted from int value to enumeration


Consider the following example:

First define an enumeration:

public enum Color : byte
    Red = 0,
    Green = 1,
    Blue = 2,

Take a look at the following code. Will the following code throw exceptions?


Let’s look at the following code. What will happen to the following code and what is the output result?

var intValue = int.MaxValue;

The output results are as follows:

It can be seen from the above results that when converting directly from the int value, the result may not be expected and exceptions will not be thrown. So how to deal with it? Let’s take another example


EnumYesParseMethod not only supportsNameString, such as in the enumeration defined earlierRed/Green, you can also supportintThe string of0/1/2Here is an example:

if (Enum.TryParse("10", out Color color))

if (Enum.TryParse("10", out Color color1)
    && Enum.IsDefined(typeof(Color), color1))
    Console.WriteLine($"Success, {color1}");
    Console.WriteLine("Can not match");

Let’s look at the output directly:

Parse from name

Let’s take another example of name conversion:

if (Enum.TryParse("Yellow", out Color color2))

This won’t have any output,TryParseWill return directlyfalse


When converting an enumeration from an int value, be careful. Even if the int value is not defined in the enumeration, the conversion will succeed. If you want to ensure that the corresponding value is defined in the enumeration, you should useIsDefinedTo ensure that the enumeration defines the corresponding value