Laurent Gabiot
Laurent Gabiot

Reputation: 1301

How to alias enum name and enum values in C#? Intended use is improving code readability

Context

I'm about to spent quite some time working with a C# API. Use of this API will imply the very frequent use of a small set of enum from that API (number of values in the hundreds range). These enum are sprinkled everywhere in the code.

I dislike the naming of these enum as I find they add a lot of noise to the code written. They are named with the following template:

SoftwareNameNameOfTheKindOfEnum.SoftwareNameNameOfTheKindOfEnumKindOfValue

A slightly modified but very similar example would be:

YZBuiltInCategoryKinds.YZBuiltInCategoryKindsOtherCategory

One enum value takes easily 50 to 60 characters, and I find them hard to read when used in the code.

I'd rather be reading something along:

NameOfTheKindOfEnum.KindOfValue

which for the example above would give:

CategoryKind.OtherCategory

Question: How to make aliases of enum in C#, aliasing not only the enum type name, but also the enum values names. Aliasing the type name is easy with a using directive, but it doesn't affect the enum values names.

Upvotes: 0

Views: 386

Answers (1)

Laurent Gabiot
Laurent Gabiot

Reputation: 1301

Edit Replaced static readonly by const thanks to @MarcGravell comment.

A solution I found is to create a set of const variables stored in a static class, one for each enum, such as:

public static class CategoryKind
{
    public const YZBuiltInCategoryKinds OtherCategory = YZBuiltInCategoryKinds.YZBuiltInCategoryKindsOtherCategory,
    // etc... add as many readonly variables as there is values for this `enum`
}

With these static classes, code like:

var myProperty = new Property(YZBuiltInPropertyTypes.YZBuiltInPropertyTypesInteger, 10, YZBuiltInCategoryKinds.YZBuiltInCategoryKindsOtherCategory);

would become

var myProperty = new Property(PropertyType.Int, 10, CategoryKind.OtherCategory);

Upvotes: 2

Related Questions