Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign invalidValue to Enum variable (why is this not throwing an Exception?)

Tags:

c#

enums

casting

I was writing some generic enum casting logic, and I came across a strange phenomenon with Enum.ToObject method:

[TestClass]
public class UnitTest1
{
    public enum FixedSet
    {
        Value1 = 1,
        Value2 = 2,
        Value3 = 3

    }

    [TestMethod]
    public void TestMethod1()
    {

        try
        {
            var intVal = 123;
            FixedSet actual = (FixedSet)Enum.ToObject(typeof(FixedSet), intVal);
            Assert.Fail("Thought an exception should have occured");
        }catch(Exception e)
        {
            //should have thrown an exception
        }
    }
}

```

I would expect this to throw some kind of exception, since 123 is not a value of the given enum type, however, I am able to set it as the value of this FixedSet variable.

Why is this allowed? I always assumed this should fail since C# is a strongly typed language, and this is a strongly defined enum...

like image 746
Nathan Tregillus Avatar asked Feb 01 '26 05:02

Nathan Tregillus


1 Answers

According to ISO IEC 23270 (2006):

In particular, any value of the underlying type of an enum can be cast to the enum type, and is a distinct valid value of that enum type.

Enumeration does not "inherit" from underlying type (it's only a syntax). According to the same ISO, enumeration implicitly inherits from System.Enum and System.ValueType.

The type System.Enum is the abstract base class of all enum types (this is distinct and different from the underlying type of the enum type)

Note that System.Enum is not itself an enum-type. Rather, it is a class-type from which all enum-types are derived. The type System.Enum inherits from the type System.ValueType (§11.1.1), which, in turn, inherits from type object

If you want to check if enum's value is valid in "common" sense, you can use Enum.IsDefined method.

like image 149
Sergey.quixoticaxis.Ivanov Avatar answered Feb 02 '26 17:02

Sergey.quixoticaxis.Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!