Reputation: 2923
I have two Enumerators and a method that takes an enumerator. They are called ABC and DEF and the method is called TestMethod(Enum myEnum). Code is below:
public enum ABC
{
Zero,
One,
Two
};
public enum DEF
{
Zero,
One,
Two
};
public void TestEnum(Enum myEnum)
{
...
}
The function TestEnum takes any enumerator. How can I test which one of the two does the passed in parameter belong to? I could blindly start testing it out with try / catch casting but sheesh that's ugly. Any cleaner ways of doing this? Thank you in advance for any help.
Upvotes: 1
Views: 249
Reputation: 1503290
How can I test which one of the two does the passed in parameter belong to?
You can just call GetType
:
Type type = myEnum.GetType();
It's not clear what you want to do with it after that, mind you.
Alternatively:
if (myEnum is ABC)
{
}
else if (myEnum is DEF)
{
}
EDIT: If you're able to change the method signature and if your callers will know the type, then as per Jeppe's comment, you could use:
public void TestEnum<T>(T value) where T : struct
{
// Use typeof(T) here
}
You can't constrain T
to be an enum type with normal C#... although there are hacky ways of writing code with such constraints applied via post-processing.
Upvotes: 6
Reputation: 4886
Mr. Skeet already nailed this but!
What about two methods.
public void TestEnum(ABC abcEnum) {
//do ABC stuff
}
public void TestEnum(DEF defEnum) {
//do DEF stuff
}
You get the branching you need but without having to worry about getting the if statement right. True it's only an if statement but what if you add enum GHI. Now there's some unaccounted for input for TestEnum to handle. Using overloaded methods you'd catch that while compiling (or even better, intellisense would catch you).
Upvotes: 1