4 ms·
clicking that link, i see a 'not all code paths return' error.
by abiox 9y ago
clicking that link, i see a 'not all code paths return' error.
- ajennings 9y agoI can see how that's unclear. That fiddle was supposed to be an example where I did exhaust all the options, so I shouldn't get a compiler error. In any case, to make the error go away, I add a "return null" or throw an exception at the end: https://dotnetfiddle.net/I7LXkW https://dotnetfiddle.net/I7LXkW Then I want to be able to add a "yellow" option to the enum and get a compiler error, but there is no error: https://dotnetfiddle.net/IIUfye https://dotnetfiddle.net/IIUfye That's the bigger problem. I should've shared that one. Can someone show me a fiddle of a C# program that compiles, but gives a compiler error when I add another value to the enum?
- int_19h 9y agoThere isn't one. You're correct, this is not something that C# can do. To be even more specific, it's not doable in C#, because enum types actually have the complete set of values of the underlying integer type. Thus, this is valid: Color c = (int)123; So enum doesn't actually limit the value domain of the integer type. It just gives names to some of the values, while still allowing all other values. If you actually mean to constrain the values as part of pre-contracts in your public API, you have to check for that yourself, e.g. via `Enum.IsDefined`. So, getting back to your scenario - "Yellow" was always an option. It's just that you gave it a name when it didn't have one before. Consequently, for switch to be truly exhaustive, it'd have to check for all 2 billion possibilities. This all is the unfortunate consequence of inheriting enum design from C++, and retaining its very low-level semantics. But now that it's there, and has been there since C# 1.0, they're stuck with it. I suspect any future advances in this area will come with a new construct that would be a "better enum" - e.g. case classes or full-fledged ADT variants. Now that the language has pattern matching, it's begging for something like this.
- ajennings 9y agoI wrote a compiler extension to help me: https://github.com/abjennings/EnumAnalyzer https://github.com/abjennings/EnumAnalyzer It doesn't analyze the control flow or anything like that. It just looks for places where I throw a certain exception, then checks the surrounding code block to make sure all the defined enum values are mentioned at least once. It definitely doesn't handle all the corner cases. But I think it's 90% of the benefit for 10% of the cost. Also, I learned to write compiler extensions...