Found the problem

We will definitely use enumerations (Enmu) in our development. Sometimes we will convert ints to enumerations, but have you ever encountered a pit when converting from ints to enumerations? Whether you have encountered one or not, please finish reading this article. Let’s start with a simple example:

public enum City: byte
{
    BeiJing= 0,
    ShangHai = 1,
    ShenZhen= 2,
    WuHan=3
}
Console.WriteLine(((City)100).ToString());
var intValue = int.MaxValue;
Console.WriteLine(((City)intValue).ToString());
Copy the code

Here I would like to ask you, the above code run error? The best way to see if there is an error is to run it. The code above produces the following output:

When an int is converted directly to an enumerated value, the result is not the exception we want it to be. How do we handle this problem? Let’s talk about the solution.

To solve the problem

The Parse method in Enum supports converting from a Name string to an enumerated value as well as a numeric string to an enumerated value, as shown in the following example:

// Convert a numeric string to an enumerated value
if (Enum.TryParse("100".out City city1)
    && Enum.IsDefined(typeof(City), city1))
{
    Console.WriteLine($" The cities are:{city1}");
}
else
{
    Console.WriteLine("Not enumerable values.");
}
// The Name string is converted to an enumeration value
if (Enum.TryParse("HongKong".out City city2))
{
    Console.WriteLine(city2.ToString());
}
Copy the code

The output of the above code is as follows:

Do you see anything in the code? We write the code as usual when the Name string is converted to an enumeration value, but when the number string is converted to an enumeration value, we use the Enum.IsDefined method to determine if city1 is what the enumeration City actually defines. Therefore, when converting from a numeric string to an enumeration, we need to be aware that the conversion will succeed even if the value is not defined in the enumeration. In this case, we should use the IsDefined method to ensure that the enumeration defines the corresponding value.