Reputation: 24789
I have an enum which is used by multiple classes. What is the best way to implement this?
Upvotes: 17
Views: 24031
Reputation: 3280
You can put an enum is a new codefile with .cs extension, for intellisense to work make sure its part of your project/solution and ofcourse it should be a public enum so that you have a solution scope for it. If intellisense is a problem , make sure you build your solution once, i had this problem once and just a rebuild solved it. Namespacing is a good option if you want to organize your code properly and you are coding a large project. The .NET framework was large. so it has enums under namespaces just for better understanding and code organization.
Upvotes: 1
Reputation: 39261
XML comments help, especially if others will use it
/// <summary>
/// Defines the types of cars we support
/// </summary>
public enum CarType
{
/// <summary>
/// VW - the peoples car
/// </summary>
Volkswagen,
Your enum name should be plural (as instructed by FxCop)
public enum CarTypes
Add numeric values and use bitwise numbering even if you don't plan to use bitwise (it's a pain to renumber later).
Volkswagen = 1,
/// <summary>
/// They own lambo... can't be all that bad
/// </summary>
Audi = 2,
/// <summary>
/// Good, cheap, reliable
/// </summary>
Toyota = 4,
Upvotes: 9
Reputation: 1584
My advice is to not use Enums at all. Use singletons instead.
Like
public class A : ISomeInterface
{
public static readonly A Instance = new A();
private A()
{
}
}
public class B : ISomeInterface
{
public static readonly B Instance = new A();
private B()
{
}
}
In most cases that works better and is better to extend later.
Best wishes
Matze
Upvotes: -9
Reputation: 2472
Here's an example of having two enums in different namespaces:
using TotallyDifferentNameSpace.Enums;
namespace EnumEx
{
class Program
{
static void Main(string[] args)
{
CarType car = CarType.Audi;
PetrolType pType = PetrolType.Diesel;
}
}
public enum CarType
{
Volkswagen,
Audi,
Toyota,
Ford,
Porsche,
Lada
}
}
namespace TotallyDifferentNameSpace.Enums
{
public enum PetrolType
{
Gasoline,
Diesel
}
}
Upvotes: 4
Reputation: 116458
I'd keep them in their own file for easy access and good organization either way.
I usually wouldn't put them in a class unless they somehow "belong" there. Like you have a Car class with an enum for the types of car, and a Road class and Bridge class that can set limits for types of car. Car.CarType
seems to be a logical organization for this...
Upvotes: 10
Reputation: 4479
Typically I just throw them into the namespace. It's what Microsoft did writing the .NET framework, so it's what I do too, for consistency you understand :)
Upvotes: 13
Reputation: 2706
Put it in its own file and just declare it:
public enum Foo { a, b, c, d }
Consider your namespacing of course.
Upvotes: 8