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.

Joshua Wieczorek
  • 655
  • 2
  • 9
  • 23
  • Duplicate of [this](https://stackoverflow.com/questions/1331739/enum-type-constraints-in-c-sharp), which is already one of any duplicates of [this](https://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint). – ForeverZer0 Jul 15 '18 at 01:11
  • Possible duplicate of [Anyone know a good workaround for the lack of an enum generic constraint?](https://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint) – ForeverZer0 Jul 15 '18 at 01:12

1 Answers1

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

Flydog57
  • 6,851
  • 2
  • 17
  • 18