Is the Compiler Wrong?
Consider the following C# program.
class Program { static void Main(string[] args) { ThisWillNotCompile(MyEnum.Foo); } private static string ThisWillNotCompile(MyEnum input) { switch (input) { case MyEnum.Foo: return “Hello, world.”; case MyEnum.Bar: return “Howdy, world.”; case MyEnum.Baz: return “Hi there, world.”; } } enum MyEnum { Foo, Bar, Baz } }
This code will not compile. The compiler returns, “Program.ThisWillNotCompile(Program.MyEnum)’: not all code paths return a value.” Is this wrong? Discuss…
Comments
Comment from Sandy
Date: June 17, 2008, 3:16 pm
Obviously the compiler just sees the enum as an int and therefore doesn’t consider the expected bounds. The language spec says “without a default: statement control is passed outside the block” … so that’s what gives it permission to puke on you.
*Should* it catch it? It would be nice, but I don’t seeing “special” cases in my code and this seems like a special case. If you extend the enum later then a part of code breaks compilation that you weren’t considering. That’s nasty.
But I could flip/flop either way on it.
Pingback from On The Other Hand » Is the Compiler Wrong? - Part II
Date: June 18, 2008, 3:43 am
[...] a simpler example of the previous post. This won’t compile either. Once again, the compiler reports that not all code [...]







Write a comment