36

How could I define an Interface which has a method that has Enum as a paramater when enums cannot be defined in an interface?

For an Enum is not a reference type so an Object type cannot be used as the type for the incoming param, so how then?

ΩmegaMan
  • 26,526
  • 10
  • 91
  • 107
PositiveGuy
  • 45,186
  • 107
  • 295
  • 464

5 Answers5

45
public enum MyEnum
{
  Hurr,
  Durr
}

public interface MyInterface
{
  void MyMethod(MyEnum value);
}

If this isn't what you're talking about doing, leave a comment so people can understand what your issue is. Because, while the enum isn't defined within the interface, this is a completely normal and acceptable design.

  • +1 I created an iEventLogTypes `class` as helper for my IEventLog `interface`. Right now it only contains an `enum`, but I can add any "types" that I need within my interface. I like sticking the enum in a "similar named" class so that the enum is more tightly bound to the specific interface, even if it's in "name only". – franji1 Oct 16 '15 at 15:12
23
interface MyInterface
{
    void MyMethod(Enum @enum);
}
Yuriy Faktorovich
  • 64,850
  • 14
  • 101
  • 138
8

Another solution could be to use Generic types:

public enum MyEnum
{
    Foo,
    Bar
}

public interface IDummy<EnumType>
{
    void OneMethod(EnumType enumVar);
}

public class Dummy : IDummy<MyEnum>
{
    public void OneMethod(MyEnum enumVar)
    {
        // Your code
    }
}

Also, since C# 7.3, you can add a generic constraint to accept only Enum types:

public interface IDummy<EnumType> where EnumType : Enum
{
    void OneMethod(EnumType enumVar);
}
Thomas Hsieh
  • 711
  • 1
  • 6
  • 26
Samuel LIOULT
  • 574
  • 5
  • 19
2

Defining an enum is like defining a class or defining an interface. You could just put it in one of your class files, inside the namespace but outside the class definition, but if several classes use it, which one do you put it in, and whichever you choose you will get "Type name does not match file name" warnings. So the "right" way to do it is to put it in its own file, as you would a class or an interface:

MyEnum.cs

namespace MyNamespace { internal enum MyEnum { Value1, Value2, Value3, Value4, Value5 }; } Then any interfaces or classes within the namespace can access it.

Dave
  • 2,927
  • 2
  • 23
  • 27
0

If you're talking about generic interfaces and the fact that C# doesn't let you constrain generic types to be enums, the answers to this question include two different work-arounds.

Community
  • 1
  • 1
Joel Mueller
  • 27,771
  • 9
  • 64
  • 86
  • It does constrain, you just can't define the type inside the interface. The same way you do when you create an interface, add a namespace that contain a specific type then add that in the parameters or return types. – Lucas Locatelli Feb 23 '15 at 19:49