Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent an Enum in an Interface?

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.


interface MyInterface
{
    void MyMethod(Enum @enum);
}

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);
}

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.