C# : Where do you define an enum

Frequently while designing classes that have methods which accept enums as parameters, a common question arrises on where to define the enum. Whether to define it inside the class or in the same level as the class.

Lets consider a class Folder which has a method List. It accepts a enum Filter and based on it prints the name of all files or directories in the Folder. We can define the enum at the same level as the Folder as below

 enum Filter{    File,    Dir}class Folder{    public Folder(string path) { /* ... */ }    public void List(Filter filter) { /* ... */ }}Folder folder = new Folder("c:\");folder.List(Filter.File);

Or define it inside the Folder class as in

 class Folder{    public enum Filter    {        File,        Dir    }    public Folder(string path) { /* ... */ }    public void List(Filter filter) { /* ... */ }} Folder folder = new Folder(@"c:\");folder.List(Folder. Filter.File);

I think that the first approach is much simpler because otherwise you have to continually type in the complete scope of the enum as Folder. Filter . This soon becomes painfull. I first had a little difficulty understanding why do people still do this. Then I figured out that there are a lot of C++ programmers who have migrated to C# and in un-managed C++ the second approach is the way to go. Lets see why

The issue with C++

If we use the same code in C++ as in the first approach then we get the following

 /*  1 */ namespace MyNameSpace/*  2 */ {/*  3 */     enum Filter/*  4 */     {/*  5 */         File,/*  6 */         Dir/*  7 */     };/*  8 */ /*  9 */     //char File[] = "c:\\foo\\bar";/* 10 */     class Folder/* 11 */     {/* 12 */     public:/* 13 */         Folder(char* path) { /* ... */ }/* 14 */         void List(Filter filter) { /* ... */ }/* 15 */     };/* 17 */ }

According to C++ spec the enum constant File and Dir is raised to the same scope as that of Filter. So effectively nowhere in the whole namespace of MyNameSpace can variables of name File or Dir can be defined. So if you uncomment the 9th line then compilation will fail indicating redeclaration of variable File.

So defining enums at the level of classes have serious consequence of namespace pollution. So C++ programmers generally put the enum declaration inside the class definition. This requires the client program to use scope resolution a bit too much even then this is worth the extra typing.

However, in C# since this is a non-issue the enum must be declared at the same level as the class.