0

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!

2
  • you are using out result which is an int type. whilst enum.tryparse expect to be outputted as an Enum. so use var result; instead Commented Mar 25, 2022 at 14:36
  • 3
    It's relatively recent that it's been possible to constrain generic types to be of an enum type, and apparently that's not been applied here. Commented Mar 25, 2022 at 14:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
        }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.