Monday, November 15, 2010

Differences between enum in C# and C/C++

Recently I encountered a confusing situation that took me by surprise while porting some old, well-proven C++ code to C#: the languages treat enumerated types differently. In C and C++, an enum defines a value type that represents a restricted set of values. An enum type can be declared just about anywhere before it is used, including statement blocks.

In C#,  an enum defines a class (i.e. types are classes), meaning it can be declared only at the namespace or class level; it cannot be defined in a statement block within a method as it can in C++. If you try, Visual Studio issues an error not about the enum definition itself, but instead at the opening brace of the method, stating '} expected' rather than something useful like 'enum cannot be defined at statement level' or even 'invalid statement'. Another unintuitive error message brought to you courtesy of Microsoft.

So if you're a C++ programmer learning C#, beware this trap. It's easily fixed by moving (and naming or renaming) your enumeration to a less narrowly scoped portion of your module, but it's annoying and unwelcome, nonetheless.