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?

Answers


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

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
    }
}

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.


Need Your Help

Knockout + Jquery Validate

jquery jquery-validate knockout.js

I'm trying to setup validation with jquery validate, and i've got the viewmodel coming back from the server, mapped to the client and successfully have knockout js binding some data.

How do you set the max height of an expanded "Chosen" element (jQuery plugin)

jquery html css html5 jquery-chosen

At the moment I'm using a Chosen JQuery widget inside a JQuery dialog box, and as soon as you open the dropdown box, the size of the dropdown causes the dialog box to overflow, causing this: (notic...