Is is safe to use Enum.Parse() regardless of current culture used in either end when passing integers

StackOverflow https://stackoverflow.com/questions/17891398

Question

For C# floating points types, I understand that one "culture effect" is that ',' may be used instead of '.', but for integers types what are the possible effects?

I ask since

 Int32.TryParse() 

will accept a CultureInfo.InvariantCulture (IFormatProvider) argument but

 (T)Enum.Parse(typeof(T), enumString, true);

does not even though Enum.Parse() accepts integers or the enum literal.

Example: A client uses Int32.ToString() with one culture and a server uses Enum.Parse() to with a different culture (current since there is no arg).

Was it helpful?

Solution

The documentation is not clear on what the actual behavior is, so I looked at the source code for Enum.Parse (in .NET 4.5). It will always use an invariant culture (not the current culture) when parsing integer values from the input string. Specifically the line to parse the integer is:

temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture);

Numeric values are identified by checking if the first character is a digit (using Char.IsDigit), '+', or '-'. So you would be safe if you convert to a string using the invariant culture on the client and use Enum.Parse on the server and they both use .NET 4.5. However, I'm not sure as to whether this is the behavior on older versions of the framework or is guaranteed for future versions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top