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.

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
public class Constants
{
  public const string SERVER_NAME = "WOODPECKER";
  public const int SERVER_TYPE = (int)ServerType.Web;
  public const float PURCHASE_PRICE = 5995.75F;
}
[/sourcecode]

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

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
Console.WriteLine("The name of the server is: " +
  Constants.SERVER_NAME);
[/sourcecode]

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.

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
public enum ServerType { Database, Web, Mail,
    Proxy, Batch, Application }
[/sourcecode]

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

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
if (Constants.SERVER_TYPE == (int)ServerType.Web)
{
  Console.WriteLine();
  Console.WriteLine("The type of the server is Web");
}
[/sourcecode]

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


Leave a Comment

Your email address will not be published.