Search code examples
c#.netinterface

C# Interface with Enum Type Parameter


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.


Solution

  • 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).