Tuesday, March 16, 2010

Read – only Fields

The readonly keyword is used to declare read – only fields. There are only two ways to assign values to read – only fields. The first way is to assign the value in the declaration statement, as in this example:
public readonly int readOnlyInt1 = 55;
The second is to use a constructor, as in this example:
public MyClass()
{
    readOnlyInt1 = 66;
}
The following example demonstrates the read – only fields.
//Example 5-11.cs
// readonly example
using  MyClass
{
    public int myRegularInt;
    public readonly int readOnlyInt1 = 55;
    public readonly int readOnlyInt2;
    public MyClass()
    {
        readOnlyInt2 = 66;
    }
    public MyClass(int l, int m, int n)
    {
        myRegularInt = l;
        readOnlyInt1 = m;
        readOnlyInt2 = n;
    }
}
class MainClass
{
    static void Main()
    {
        MyClass obj1 = new MyClass(11,23,33); //OK
        Console.WriteLine(“obj1 fieds are: {0}, {1}, {2}” , obj1.myRegularInt, obj1.readOnlyInt1, obj1.readOnlyInt2);
        MyClass obj2 = new MyClass();
        obj2.myRegularInt = 44; //OK
        Console.WriteLine (“obj2 fields are: {0}, {1}, {2}”, obj2.myRegularInt, obj2.readOnlyInt1, obj2.readOnlyInt2);
    }    
}
Notice in this example that we cannot change the value of the read – only field in the Main method by using a statement like this:
obj1.readOnlyInt1 = 55; //error
Note:  - The difference between a read – only field and a constant field is that we can change the value of the first by using the allowed ways mentioned above. The constant fields, however, cannot be changed after declaration.

No comments:

Post a Comment