Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic enum as method parameter

Tags:

c#

enums

generics

Given a constructor

public MyObject(int id){
    ID = id;
}

And two enums:

public enum MyEnum1{
    Something = 1,
    Anotherthing = 2
}

public enum MyEnum2{
    Dodo = 1,
    Moustache= 2
}

Is it possible to pass in a generic enum as a parameter of the constructor? I'm looking for a solution along the lines of:

public MyObject(enum someEnum){
    ID = (int)someEnum;
}

So you can do:

var newObject = new MyObject(MyEnum1.Something);
var anotherObject = new MyObject(MyEnum2.Dodo);
like image 862
Tom Gullen Avatar asked Sep 08 '16 13:09

Tom Gullen


People also ask

Can you use an enum as a parameter in Java?

Enum as a method argument or argument in javaIn the examples below i will demonstrate you how to use Enum type as a method parameter, how to return a value from any Enum type, the method will be universal method which will work with any Enum class you give it to it.

Can you declare enum in method?

We can an enumeration inside a class. But, we cannot define an enum inside a method.

Can enums be generic?

enum is treated as a special type and Microsoft haven't implemented this (yet). However, it is possible to use enums in generics. The MSDN article for Enum gives the following type definition for the class Enum .

Can enum be type parameterized?

E is a subclass of some parameterization of Enum and, in particular, the parameterization of Enum on the subclass type itself. To say this again, what it does is to require that any invocations of the Enum type are by subclasses of some parameterization of the Enum type.


3 Answers

Another option would be:

public MyObject(Enum someEnum){
    ID = Convert.ToInt32(someEnum);
}

This way you can use it like you requested without having to cast to int each time you call your contstructors:

var newObject = new MyObject(MyEnum1.Something);
var anotherObject = new MyObject(MyEnum2.Dodo);
like image 179
serhiyb Avatar answered Oct 18 '22 21:10

serhiyb


Why do you want to pass the enums, while you could pass integers ?

var newObject = new MyObject((int)MyEnum1.Something);
var anotherObject = new MyObject((int)MyEnum2.Dodo);

and use your first constructor :

public MyObject(int id){
    ID = id;
}
like image 23
Martin Verjans Avatar answered Oct 18 '22 22:10

Martin Verjans


Just use a generic constructor:

class MyObject<T> {

    public MyObject(T someEnum) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) 
            throw new ArgumentException("Not an enum");
        ID = Convert.ToInt32(someEnum);
    }
}

Now you can easily call it like this:

var m = new MyObject<MyEnum>(MyEnum1.Something);

But easier would be to pass the enum as integer to the constructor as mentioned in other answers.

like image 34
MakePeaceGreatAgain Avatar answered Oct 18 '22 21:10

MakePeaceGreatAgain