Constants and Enums in C#

Constants come in handy when you need to store values that will be used frequently within the system and at the same time will not change often, if ever. You want to avoid hard coding values in you code. It makes maintenance and debugging very difficult.

You can create a constants class and then access the value like static variables. The class would look like this.

public class Constants
{
  public const string SERVER_NAME = "WOODPECKER";
  public const int SERVER_TYPE = (int)ServerType.Web;
  public const float PURCHASE_PRICE = 5995.75F;
}

And you can access the value stored within it like this.

Console.WriteLine("The name of the server is: " +
  Constants.SERVER_NAME);

Enums on the other hand are used to contain a set of named constants. Basically, it lets you give names to a sequence of integers.

public enum ServerType { Database, Web, Mail,
    Proxy, Batch, Application }

The above line would set Database = 0, Web = 1, Mail = 2, etc… I can access the their values like this.

if (Constants.SERVER_TYPE == (int)ServerType.Web)
{
  Console.WriteLine();
  Console.WriteLine("The type of the server is Web");
}

I use enums to make my code more readable and if code is easier to read then it will be easier to maintain and enhance.

Download the source