RE: C# : Where do you define an enum

Paul Kinlan

There is an interesting article over on Abhinaba’s weblog about where you would place the declaration of the enum. I personally don’t agree with his argument. He says that his ideal way of defining the placement of an enum is at the level of the class and not inside the class.

His basic argument that typing the class name infront of the enum can become a pain. I don’t really care that it can be a pain, that is what intelisense is there for. Having the enum defined in the class is better in my opinion because it means that there will be fewer abiguity problems if you need to use another enum with the same name from another class. It is, in my opinion also easier to read.

Anyway, below is a snippet of his journal entry. To see what he has to say visit his blog, and see if you agree with me or not.

Email me: paul.kinlan@gmail.com

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);


[Via MSDN Blogs]

Paul Kinlan

Trying to make the web and developers better.

RSS Github Medium