Using Enums for constant values

Have you ever found yourself using c# const values to remove the risks associated with using copies of string literals throughout your code base?

Example:

public static class VehicleTypesConsts {
 public const string Car = 'Car';
 public const string Motorbike = 'Motorbike';
 public const string Truck = 'Truck';
}

In a situation like this it’s quite easy to replace these const values with a C# enum and use the System.Enum.GetName static method to return Enum properties name.

public enum VehicleTypesEnum {
  Car,
  Motorbike,
  Truck,
}

Calling

Enum.GetName(typeof(VehicleTypesEnum), VehicleTypesEnum.Car)

will return the string value “Car”.

Looking at this syntax you could be forgiven for thinking why bother? It’s too much hassle and looks puss.

Well using C# 3.0 extension methods you can provide a convenience method to all Enums to return the enum string representation.

public static class EnumExtensions {
  static public string GetName(this Enum enumeration) {
    return Enum.GetName(enumeration.GetType(), enumeration);
  }
}

Now you can just write:

VehicleTypesEnum.Car.GetName()

and it will return the string “Car”.

The following test method shows illustrates the varying ways to achieve the same result:

        [TestMethod]
        public void Test()
        {
            string expected = 'Car';
            Assert.AreEqual(expected, VehicleTypesConsts.Car);
            Assert.AreEqual(expected, Enum.GetName(typeof(VehicleTypesEnum), VehicleTypesEnum.Car));
            Assert.AreEqual(expected, VehicleTypesEnum.Car.GetName());
        }
Posted in C# by Ben at October 13th, 2008.

One Response to “Using Enums for constant values”

  1. viiviiviivii says:

    I tells ya, WebMacro was doin that before you were born! :)

    Anyway, yeah that makes it a lot easier to write up stuff, so long as people don’t get all confused with it.

Leave a Reply