Home > Net >  How to pass generic type as parameter to Enum.Parse()
How to pass generic type as parameter to Enum.Parse()

Time:11-29

I have a class with a generic method:

public record OperationCollectionGeneric<OPERATIONTYPE> where OPERATIONTYPE: notnull, Enum
{
    public OPERATIONTYPE Group { get; }

    public OperationCollectionGeneric(string part1, string? part2 = null, string? part3 = null)
    {
        Group = Enum.Parse<OPERATIONTYPE>(part1, true);
    }

The Enum.Parse() method has the following error:

Error CS0453 The type 'OPERATIONTYPE' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'Enum.Parse(ReadOnlySpan, bool)'

How can I pass the make sure that OPERATIONTYPE parameter is of type Enum

I tried to use the where keywork to set the enum type for the OPERATIONTYPE but it does not work.

CodePudding user response:

Enum.Parse is restricted to struct's, so change generic constraints to match it:

public record OperationCollectionGeneric<OPERATIONTYPE> where OPERATIONTYPE : struct, Enum

CodePudding user response:

OPERATIONTYPE must be a non-nullable value type, but System.Enum is a reference type.

  • Related