I usually make enumerations separate from classes, but when my CS teacher was teaching us about enums, he put it inside the class, and when it came time to set a variable of the enum outside of the class, he told us to just pass a string to the class evaluate that with a method inside the class itself. Is there any reason why one would do this? Is it bad practice to put enums outside of the class in which it is used?

Sorry if it's hard to understand what I'm trying to say. I'll try to make some code snippets to make it easier to understand.

Here we go:

What I usually do:

enum AnEnum {
	Bla,
	Blah
}

public class A {
	AnEnum anEnum;

	public A(AnEnum newAnEnum) {
		anEnum = newAnEnum;
	}
}

What he told us to do (I don't know if that string evaluation is 100% right, but this is pretty much it)

public class A {
	enum AnEnum {
		Bla,
		Blah
	}
	
	AnEnum anEnum;
	
	public A(string newAnEnum) {
		if(newAnEnum == "Bla") anEnum = AnEnum.Bla;
		else anEnum = AnEnum.Blah;
	}
}

Edited 6 Years Ago by Xeros606: n/a

I prefer your method personally. I go one step further and put enums in their own file with an extension of the TypeConverter class to perform casts between an enum and a string.

There is no reason why you can't, but it depends on the accessibility you need for the enum. If the namespace directly contains the enum than any object in that namespace has access to the enum. When its contained in a class, depending on its access modifier it may or may not be available to all the objects in that namespace.

Typically you would put the enum inside the class if the class encapsulates the extent of the usage of the enum. If the enum has common items to the application that don't explicitly require the use of the class then its up to the developer to make the call.

My opinion too is your teacher's method is a waste of time, and making things too complex when they can be done simpler.

My usual practice is to put them in a separate file (not a separate class, but inside the same namespace) so they would be accessible from everywhere.

If your enum only has relevance for a particular class, leave it inside that class.
But most of the time enums have the tendency to be of a more general nature ( my experience ) so I think defining them outside a class is the way to go.

This article has been dead for over six months. Start a new discussion instead.