Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# enum array accepting a wrong value [duplicate]

Tags:

c#

.net

enums

I was working on a web service method that will receive an array of ints as parameter, and then, inside the method, I converted the values in the array into enum values, and stored them in a enum list. However, when a value that's not in the enum is passed, it is added to the enum list with no problems. No InvalidCastException, nothing. I made a test project that looks like this:

static class Program
{
    static void Main(string[] args)
    {
        List<TestValues> values = new List<TestValues>() {
            TestValues.Value1,
            TestValues.Value2,
            (TestValues)15
        };

        foreach (var val in values)
            Console.WriteLine(val);

        Console.Read();
    }

    enum TestValues
    { 
        Value1 = 2,
        Value2 = 4,
        Value3 = 8
    }
}

When I run it, the output is:

Value1
Value2
15

For my web service, I'll implement a validation, so this will never hapen at all. But... this is weird! Shouldn't the runtime throw a InvalidCastException or ArgumentOutOfRangeException, or something similar? Since I got a list of enums (and not int values), I want the values to be limitted to the values of the enum (that's what an enum is for).

Am I missing something? Is this a .NET bug, a C# bug or is there something I don't know with enums?

like image 506
Raphael Avatar asked Aug 25 '11 18:08

Raphael


1 Answers

You can assign any value to an enum that the underlying type allows. By default, the underlying type is int, so you can assign any int value to the enum.

The main reason for this is because if you have a [Flags] enumeration, you want to be able to assign composite values:

[Flags]
public enum MyFlags
{
    A = 1,
    B = 2
}

MyFlags flags = (MyFlags)3; // Equivalent to setting A and B

Preferably you'd just use the enumeration values to do that, though:

MyFlags flags = MyFlags.A | MyFlags.B; // Sets flags to 3

It's important to note, of course, that the [Flags] attribute isn't required to enable this assignment. All enums have this property, by design.

As pointed out by a number of people, you can use Enum.IsDefined() to determine if a particular value is valid for a given enum. That should help with your validation.

like image 94
dlev Avatar answered Oct 12 '22 13:10

dlev