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?
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 enum
s 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.
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