Lukas
Lukas

Reputation: 2923

Evaluate enum parameter

I have two Enumerations and a method that takes an enumeration as a parameter. They are called ABC and DEF and the method is called TestMethod(Enum myEnum). Code is below:

public enum ABC
{
    Zero = 0,
    One = 1,
    Two = 2
};

public enum DEF
{
    Three = 3,
    Four = 4,
    Five = 5
};

public int TestEnum(Enum myEnum)
{
    int returnValue = ??? // How do I get the value out of this enum that can be either ABC or DEF?
    bool randomTestBool = returnValue > 3;
    return returnValue
}

public void CallerFunction()
{
    int whatsMyInt = TestEnum(DEF.Four);
}

From CallerFunction() I call TestEnum() function and pass in one of the two (ideally way more) enumerations. I need to find out how to obtain the value in integer format so I can compare it within the function. Now, if this was a single type of an enumeration, i.e. if the function was TestEnum(DEF myDefEnum) then this would be easy, however, the function needs to handle multiple Enum types. Thanks to a previous response, I learned that to get a type of the enum I can do one of two things:

1) bool isThisDef = myEnum is DEF; but I am curious if there is a more universal way than creating a scenario for each and every Enum type. Perhaps something like this

2) Type myEnumType = myEnum.GetType(); but I am not sure what to do with this now. Any help is greatly appreciated. =) By the way, string testString = myEnum.toString(); genereates an error :\

Upvotes: 1

Views: 705

Answers (4)

Trisped
Trisped

Reputation: 6005

You could try:

int returnValue = Convert.ToInt32(myEnum);

A better option in my mind is to explicitly declare ABC and DEF as integer types:

public enum ABC : int
{
    Zero = 0,
    One = 1,
    Two = 2
};

public enum DEF : int
{
    Three = 3,
    Four = 4,
    Five = 5
};

Then just use int returnValue = (int)myEnum;.
To be safe you would have to check the type of the enum provided so the performance gains would be small if any(unless you can guarantee that all enums which can be passed in are based on the integer type, then no check would be required).

Upvotes: 0

horgh
horgh

Reputation: 18563

I guess this behaviour is not as much reliable, as it probably can be changed in further releases of .Net, but it also returns the underlying value:

int returnValue = myEnum.GetHashCode();

P.S.: Using GetHashCode for getting Enum int value, i.e. don't do this...

Upvotes: 1

Eric J.
Eric J.

Reputation: 150228

You simply write

int returnValue = (int)(object) myEnum;

Upvotes: 2

L.B
L.B

Reputation: 116188

public int TestEnum(Enum myEnum)
{
    return (int)(object)myEnum;
}

Upvotes: 4

Related Questions