Enum Field Management

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 the method to only accept A and B ( C is considered the wrong value), but I need C in my Enumeration , because other methods can take it as the right value. What is the best way to do this?

+4
source share
3 answers

I wouldn’t refuse 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 might call:

 Method((Enumeration) -1); 

and that will do your check. You always need to know that an enumeration is just a collection of named integers, but any integer of the right base type can be transferred to an enumeration type.

+6
source

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, you can use code contracts .

+5
source

As mentioned in paulsm4, you can define:

 public enum EnumSubset { A = Enumeration.A, B = Enumeration.B, } 

And use:

 public void method(EnumSubset e) { } 
+1
source

All Articles