Home > Net >  Enum.TryParse Run-time exception
Enum.TryParse Run-time exception

Time:03-26

we've found an exception in our logs and its unclear to us how this code could be valid, can someone please explain why this codesnippet results in an Run-time exception instead of being a Compile-time error?

    string variant = "Variant";
    int result;
    Enum.TryParse(variant, out result);

Link to dotnetfiddle: https://dotnetfiddle.net/XWhkz3

Thanks in advance,

Marcel!

CodePudding user response:

If you check the documentation for Enum.TryParse in .Net you can see the method signature:

public static bool TryParse<TEnum> (string value, out TEnum result) where TEnum : struct;

I.e. it is only constrained to struct types, and int fulfills that requirement. Documentation also contains

ArgumentException

TEnum is not an enumeration type.

So it is working as intended.

The Enum constraint was added in c# 7.3, but it does not look like Enum.TryParse is making use of it. C# and the compiler have improved over the years, and this code would likely not compile if TryParse was written today. But backward compatibility is important, so I kind of understand if they do not change existing behavior without a very good reason.

CodePudding user response:

You have to declare which enumType result is. you cannot use result as type int as an out variable on Enum.TryParse

public enum ExampleEnum
{
    Variant
}
public class Program
{


        public static void Main()
        {
            string variant = "Variant";
            ExampleEnum result;
            Enum.TryParse(variant, out result);
        }

}
  • Related