0
 //TechTeam is enum type
 //This line returns the enumvalue as out param, for the matching stringvalue.

 Enum.TryParse(stringvalue, out TechTeam tt);

It works perfectly. Now if I turn it to generic I am using

private T enumparse<T>(string state)
    {
        Enum.TryParse<T>(state, out T stateout);
        return stateout;
    }

it throws error.

I changed the code to :

 private T? enumparse<T>(string? state) where T: System.Enum
    {
        Enum.TryParse<T>(state, out T stateout);
        return stateout;
    }

It says the Type T must be a non nullable value.

Venkat
  • 1,702
  • 2
  • 27
  • 47
  • 1
    The accepted answer is incomplete, though, as it could allow `System.Enum` itself. You also need the `struct` constraint to prevent `System.Enum` from being allowed. [This answer](https://stackoverflow.com/a/28527552) is the one that's complete and correct. – madreflection Jun 02 '23 at 16:27
  • 1
    "it throws error" is never sufficient information in a Stack Overflow question. Always *always* provide the details of the error. – Jon Skeet Jun 02 '23 at 16:29

1 Answers1

0

Did you try setting a type constraint? I'm pretty sure there is a variation that can work with Enum.

private T enumparse<T>(string state) where T : struct, Enum
{
    Enum.TryParse<T>(state, out T stateout);
    return stateout;
}
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466