C# Classes Explained - Constants
(Page 5 of 6 )
Sometimes you know the value that you want to assign to your fields, and you need these values to remain unchanged. For example, in the employee class you may have a field for the maximum overtime hours per week, which will never change, and this information is available at design time. What you do? Use the "const" keyword to declare the field as constant, which means that its value will not change; it must be available at design time.
public class Employee
{
public decimal Salary;
public const int MaxOverTimeHours = 10;
}
Note that the value of the constant field must be literal, so you can't get the value as a return value from a method call. Load the ILDASM Tool, navigate to the Employee class, and double click the MaxOverTimeHours field.

This is the MSIL declaration for the constant field MaxOverTimeHours, and as you can see, it has been assigned the value (0xA) 10. Now let's try to use this field.
public class EmployeeTest
{
static void Main(string[] args)
{
Console.WriteLine(Employee.MaxOverTimeHours);
Console.ReadLine();
}
}
From the above constant field declaration, you can see that it's a static field, which means that you can't access the field with an object reference. You have to use the class name in order to access the static members. Think about it for a minute: why do we need an instance variable for a field whose value will never change? It will create a lot of unnecessary memory spaces, so C# defines it as static, because it will never change. Load the EmployeeTest class with the ILDASM tool and get to the main method:

The highlighted MSIL Instruction pushes the value 10 onto the stack, and the next Instruction calls the Console::WriteLine(Int32) method to print this value. As you can see, we don't have the MaxOverTimeHours constant field here; instead, the C# compiler replaces the field with the value.
Next: Static members >>
More C# Articles
More By Michael Youssef