I have an enum
:
public enum Enumeration
{
A,
B,
C
}
And a method that takes one argument of type Enumeration
:
public void method(Enumeration e)
{
}
I want that method
can accept only A
and B
(C
is considered a wrong value), but I need C
in my Enumeration
because other methods can accept it as right value. What is the best way to do this?
I wouldn't reject just C
. I would reject any value other than A
and B
:
if (e != Enumeration.A && e != Enumeration.B)
{
throw new ArgumentOutOfRangeException("e");
}
This is important, as otherwise people could call:
Method((Enumeration) -1);
and it would pass your validation. You always need to be aware that an enum is really just a set of named integers - but any integer of the right underlying type can be cast to the enum type.
Throw an exception:
public void method(Enumeration e)
{
if (e != Enumeration.A && e != Enumeration.B) {
throw new ArgumentOutOfRangeException("e");
}
// ...
}
If you are using .NET 4.0 or higher then you could use code contracts.
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