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);
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.
We can an enumeration inside a class. But, we cannot define an enum inside a method.
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 .
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.
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);
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With