Stacked
Stacked

Reputation: 7336

What's the best practice to code shared enums between classes

namespace Foo
{
    public enum MyEnum
    {
        High, Low
    }

    public class Class1
    {
        public MyEnum MyProperty { get; set; }
    }
}

MyEnum is declared outside Class1 cause I need it here and in other classes

Seems good, but what if I decide later to delete the file containingClass1?

MyEnum declaration will be lost!!

What's the best practice to code shared enums between classes?

Upvotes: 9

Views: 13367

Answers (3)

Piotr Śródka
Piotr Śródka

Reputation: 523

From my experience it is also good to add explicit values to fields in case you store them in database as integers, because changing the order or adding/deleting value in between may end up in runtime fail:

namespace Foo
{
    public enum MyEnum
    {
        High = 1, 
        Low = 2
    }
}

Also notice I start from 1 to be aware that uninitialized variable is not treated as correct enum value. Another idea is to add None = 0 value.

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

The best practice is creating separate file for each class, enum, or other type.

MyEnum.cs

namespace Foo
{
    public enum MyEnum
    {
        High, 
        Low
    }
}

Class1.cs

namespace Foo
{
    public class Class1
    {
        public MyEnum MyProperty { get; set; }
    }
}

Upvotes: 30

Oded
Oded

Reputation: 499002

What's the best practice to code shared enums between classes?

Have your enumerations each in a file of its own, with the same name as the enumeration.

// Foo\MyEnum.cs
namespace Foo
{
    public enum MyEnum
    {
        High, Low
    }
}

Upvotes: 5

Related Questions