2

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.

2
  • You need where OPERATIONTYPE: struct, Enum. The constraint you have lets someone do OperationCollectionGeneric<Enum>, where you literally pass the Enum type Commented Nov 28, 2022 at 13:56
  • "must be a non-nullable value type". You probably fixated on the "not-nullable" bit, but the important part was "value type"; struct defines a value type. Commented Nov 28, 2022 at 15:00

2 Answers 2

3

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

public record OperationCollectionGeneric<OPERATIONTYPE> where OPERATIONTYPE : struct, Enum 
Sign up to request clarification or add additional context in comments.

Comments

-1

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

1 Comment

System.Enum is a very special type which inherits from another very special type System.ValueType - base class for every value type.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.