BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Read-Only Fields

The readonly keyword permits class and structure fields to be configured so that their values cannot be modified after they have been initialised. This seems similar to the functionality provided by constants. However, there are several key differences.

Fields

Fields are simply variables that are declared directly within the code block of a class or a structure. Fields can be defined with various scopes, from private fields that are accessible only within the current class to public fields that provide similar functionality to simple properties. Such fields use less code to implement that a full property but at the cost of some functionality, such as the ability to perform data binding.

Read-Only Fields

A read-only field is declared with the addition of the readonly keyword. This type of field can only have its value set directly in its declaration or from within a constructor of its containing class. An attempt to set its value from any other location causes a compilation error.

Read-only fields differ from constants in several manners. One key difference is that constants are evaluated during compilation. Their values can never be changed at run-time and so are always the same no matter which object is referring to them. Read-only field values cannot be changed, except during construction at run-time. This means that many objects can be instantiated from the same class with each having different read-only values.

Another key difference between read-only fields and constants is that fields can be static or instance values. They can also contain any type of value, including reference types. It should be noted that a read-only field containing an object can have its properties modified. However, the reference itself cannot be changed to that of another object.

Examples

The first example shows the creation of a public read-only field in a class. In this case the value of the field is initialised within the declaration:

class Employee
{
    public readonly int PayrollNumber = 1001;
}

The second example is more useful. In this case, the employee's payroll number is set during instantiation using a constructor. Once set, the payroll number is fixed for the life of the object. Multiple Employee objects could be created, each with a different read-only payroll number.

class Employee
{
    public readonly int PayrollNumber;

    public Employee(int payrollNumber)
    {
        PayrollNumber = payrollNumber;
    }
}

To demonstrate that the field is read-only once set in the constructor, try compiling the following code in the Main method of a console application. The compilation fails with an error indicating that the field cannot be modified in the second line of code.

Employee emp = new Employee(1001);
emp.PayrollNumber = 1002;
20 October 2008