Tuesday 29 November 2011

C# readonly fields

The concept of constant variables is present in almost all of the programming languages. Just to recall, constant variables are those variables whose values are fixed and cannot be changed.

readonly fields is a relatively new concept in C#. Sometimes we may have some variable whose value we need to fix, but the value is not known until runtime. In these situations C# readonly fields come to help us. A readonly field is more flexible than a simple constant variable. Please note that in C# we use the const keyword to declare a variable as constant. A readonly field helps us in situations where we need a field to be constant but also need to carry out some calculations to determine its initial value.

The rule is very simple. We can assign values to readonly fields inside a constructor. Do not do it anywhere else or an error will result. A readonly field can be static or non-static. A static readonly field is shared among all instances of the class and it can also be used without creating an instance of the class. On the other hand a non-static readonly field is an instance field and is tied to a single object of the class.

Example:

public class ReadOnlyEx
{
public readonly int count;
public ReadOnlyEx()
{
count = 1;
}
}

The above code is legal. Now consider the following piece of code:

public class ReadOnlyEx
{
public readonly int count;
public ReadOnlyEx()
{
......
}
public SomeMethod()
{
count = 1; //Compile time error
}
}

The above code is not valid. It will generate a compile time error. readonly fields can only be assigned a value inside constructors. If you do not provide a value to a readonly field inside a constructor, it will contain the default value, depending on its data type or the value you assigned to it while declaring the field, if any. This rule applies to both statice readonly fields and the non-static readonly fields.

No comments:

Post a Comment