Thursday, October 21, 2010

ReadOnly Modifier

ReadOnly is a modifier which can be use to declare fields. We can initialize readonly variable either at the time of declaration or through constructor.

ReadOnly fields can be used for runtime constants as we can declare value through constructors.

For ex:
I have a class which contains two readonly variables.
class TestReadOnly
{
public readonly int a = 10;
public readonly int b;

public TestReadOnly()
{
b = 15;
}

public TestReadOnly(int newB)
{
b = newB;
}
}

I have another class, where i have created an object of TestReadOnly class.
class Program
{
static void Main(string[] args)
{
TestReadOnly test = new TestReadOnly();
Console.WriteLine(test.a);
Console.WriteLine(test.b);
test = new TestReadOnly(20);
Console.WriteLine(test.b);
Console.ReadLine();
}
}

Whenever, I want to reassign the value to a readonly variable, I have to call the parametrized constructor of the class and pass the new value.

No comments:

Post a Comment