Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.TryParse returns true for any numeric values

I'm running into a behavior I wasn't expecting when using Enum.TryParse.

If I have an enum:

public enum MyEnum
{
  ValueA,
  ValueB,
  ValueC
}

And then I pass a numeric value (as a string) into Enum.TryParse, like:

MyEnum outputEnum;
bool result = Enum.TryParse("1234", out outputEnum);

Despite the string "1234" not being a possible value, result will come back as true, and my outputEnum will have a value of 1234.

Is there a way I can avoid this sort of behavior? I'm trying to write a function which will process arbitrary string input as an enum, and this has thrown a bit of a monkeywrench in my bad-input detection.

like image 830
mweber Avatar asked Jul 19 '11 02:07

mweber


People also ask

What does enum TryParse return?

Definition. Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

Is enum TryParse case sensitive?

MyEnum. TryParse() has an IgnoreCase parameter, set it true. Yes I am aware that Enum. Parse has an ignorecase flag.

Can numbers be enums?

Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.

What is the default value of enum?

The default value for an enum is zero.


2 Answers

This behavior is by design.

The documentation says:

. If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

Call Enum.IsDefined to veryify that the value you parsed actually exists in this particular enum.

If you're dealing with [Flags] enums (bitmasks), it'll get more complicated.

like image 164
SLaks Avatar answered Oct 02 '22 14:10

SLaks


Use it like this

bool result = Enum.TryParse("1234", out MyEnum outputEnum) && Enum.IsDefined(typeof(MyEnum), outputEnum);

The value of result will be false but the value of outputEnum is still 1234

like image 24
Abbas Ghomi Avatar answered Oct 02 '22 15:10

Abbas Ghomi