Beware of pits in enum parse

Time:2021-8-14

Beware of pits in enum parse

Intro

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

Sample

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?

Console.WriteLine(((Color)10).ToString());

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

var intValue = int.MaxValue;
Console.WriteLine(((Color)intValue).ToString());

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

ParseSample

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))
{
    Console.WriteLine(color.ToString());
}

if (Enum.TryParse("10", out Color color1)
    && Enum.IsDefined(typeof(Color), color1))
{
    Console.WriteLine($"Success, {color1}");
}
else
{
    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))
{
    Console.WriteLine(color2.ToString());
}

This won’t have any output,TryParseWill return directlyfalse

More

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

Reference