0

I get that my enum in this example is an Integer, but this still seems very wrong. I expected an ArgumentException:

class Program {
    enum Testing {
        Zeroth,
        First,
        Second,
        Third
    }
    static void Main(string[] args) {
        Testing result = Testing.Zeroth;
        var toTest = "17";
        result = (Testing)Enum.Parse(typeof(Testing), toTest);
        Console.WriteLine(result);  // Output: 17
        Console.ReadLine();
    }
}

The following does throw the argument exception I expected:

    class Program {
    enum Testing {
        Zeroth,
        First,
        Second,
        Third
    }
    static void Main(string[] args) {
        Testing result = Testing.Zeroth;
        var toTest = "Seventeen";
        result = (Testing)Enum.Parse(typeof(Testing), toTest);
        Console.WriteLine(result);
        Console.ReadLine();
    }
}

And that takes the cake for me.

argyle
  • 1,319
  • 2
  • 14
  • 28
  • 1
    No, it is not a bug. There is an issue with your understanding though. – leppie Jan 29 '15 at 16:05
  • .NET doesn't check ranges of enums, cause it take a long time. Imagine f.e. the enum with 1000 items and values 1, 5, 3, 17, 28, ... and so on. – Mark Shevchenko Jan 29 '15 at 16:07
  • 1
    @MarkShevchenko It certainly violated the principle of least surprise. You would think a variable, strongly typed to an enum, set by parsing through the Enum.Parse() method, would actually have meaning in terms of that enum. – argyle Jan 29 '15 at 16:09
  • 1
    @MarkShevchenko the question is not about ranges, but `Enum.Parse` method – ie. Jan 29 '15 at 16:09
  • @ie. The `Enum.Parse` doesn't check values, as well as all other methods. Nothing surprising. – Mark Shevchenko Jan 29 '15 at 16:11
  • @MarkShevchenko Yet, if I give Guid.Parse() something that isn't a Guid, I get an ArgumentException. I give Enum.Parse() something that doesn't resolve to the enum and yet I still get a variable typed to that enum with a value that is invalid in relation to the enum. – argyle Jan 29 '15 at 16:12
  • 1
    @MarkShevchenko agree, nothing surprising. I just noted that parse method irrelevant to the check of the ranges. – ie. Jan 29 '15 at 16:14
  • @jeromeyers, I agree. But C# is still used for industrial programming, therefore it doesn't contain some good bot not very fast decisions. And you always can add your own checking, if you need. – Mark Shevchenko Jan 29 '15 at 16:14
  • 1
    @jeromeyers: Use `Enum.IsDefined` – leppie Jan 29 '15 at 16:17

0 Answers0