3

Is it possible to pass an enum as a type parameter for an interface, or is there a way I can achieve the same thing a different way?

E.g.

public interface IServiceResponse<R, enumServiceID> {}

Thanks in advance.

2

1 Answer 1

2

You're declaring the interface so the Type Parameters are symbolic representations of a type, not an actual concrete type. You can put a type parameter that you expect to be an enum type (say TEnum), and then constrain it to be a Value Type (where TEnum : struct), but, unfortunately you can't constrain it to be an enum. Once you do that, you can declare a class the implements that interface with a concrete enum type:

public class MyServiceResponse : IServiceResponse<MyRType, EnumServiceId> {  }

UPDATE

As noted by @BJMeyers in the comments, C# now supports Enum constraints on type parameters. As a result, you can do something like this now:

public class MyServiceResponse : IServiceResponse<MyRType, TEnumService> where TEnumService : struct, System.Enum 
{
    public TEnumService EnumServiceId { get; set; }
    // ... more code here ...
}

I'm not sure if that's what you want, but if it is, you can do it. Note, the struct in the where constraint is important (remember that System.Enum is a class, not a struct).

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

3 Comments

Noteworthy: C# 7.3 supports the where T : Enum constraint.
Alleluia. I've silently asked for that so many times over the years. Thanks for letting me know!
@BJMyers Finally, glad to have learned that, been long overdue. Now all we need is "numeric" type constraints...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.