Constant and ReadOnly variable

For Constants and Read-Only variables there value once assigned cannot be changed.
Then what is the difference between them..?

Let me explain by a example:
Example:

class DiffConstant
{
const int x = 1;
// Write the remaining code
}

when this class is compiled all the places where 'x' is there it will be replaced by '1'. The value for the constant has to be given at the time of declaration itself.

In the case of Read only data, we can set the value in the constructor.

Example:

public class DiffReadOnly
{
private readonly int x;
public DiffReadOnly(int y)
{
x= y;
}
}

***************
DiffReadOnly a = new DiffReadOnly(5);
DiffReadOnly b = new DiffReadOnly(6);
DiffConstant c = new DiffConstant(7);
DiffConstant d = new DiffConstant(8);
***************

In this case, at the time object creation, we can set the value for the 'x'. Here the value of 'x' in the object a is 5 and the value of 'x' in object b is 6. And the value of x in both objects c and d is '1'.
So a read-only variable is also known as runtime Constant.
And in simple the basic difference is, in the case of constant, the value will be same across the objects of that class, but it may differ in the case of read-only variables.

Comments

Popular posts from this blog

Network Security: LAN manager authentication level

Cisco AnyConnect Secure Mobility Client - VPN service not available. The VPN agent service is not responding