Casting ints to enums in C#

前端 未结 12 2146
北荒
北荒 2020-12-05 02:30

There is something that I cannot understand in C#. You can cast an out-of-range int into an enum and the compiler does not flinch. Imagine this

12条回答
  •  余生分开走
    2020-12-05 02:59

    Not sure about why, but I recently found this "feature" incredibly useful. I wrote something like this the other day

    // a simple enum
    public enum TransmissionStatus
    {
        Success = 0,
        Failure = 1,
        Error = 2,
    }
    // a consumer of enum
    public class MyClass 
    {
        public void ProcessTransmissionStatus (TransmissionStatus status)
        {
            ...
            // an exhaustive switch statement, but only if
            // enum remains the same
            switch (status)
            {
                case TransmissionStatus.Success: ... break;
                case TransmissionStatus.Failure: ... break;
                case TransmissionStatus.Error: ... break;
                // should never be called, unless enum is 
                // extended - which is entirely possible!
                // remember, code defensively! future proof!
                default:
                    throw new NotSupportedException ();
                    break;
            }
            ...
        }
    }
    

    question is, how do I test that last case clause? It is completely reasonable to assume someone may extend TransmissionStatus and not update its consumers, like poor little MyClass above. Yet, I would still like to verify its behaviour in this scenario. One way is to use casting, such as

    [Test]
    [ExpectedException (typeof (NotSupportedException))]
    public void Test_ProcessTransmissionStatus_ExtendedEnum ()
    {
        MyClass myClass = new MyClass ();
        myClass.ProcessTransmissionStatus ((TransmissionStatus)(10));
    }
    

提交回复
热议问题