Manage Enum field

c#, enums

Solution

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.

Problem

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?

Original source