Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage Enum field

Tags:

c#

enums

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?

like image 332
Nick Avatar asked Dec 16 '22 22:12

Nick


2 Answers

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.

like image 200
Jon Skeet Avatar answered Dec 30 '22 01:12

Jon Skeet


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.

like image 41
Mark Byers Avatar answered Dec 30 '22 01:12

Mark Byers