Constants:
Constants are values which are known at compile time and do not change. (To create a constant value that is initialized at runtime, use the
readonly keyword.) Constants are declared as a field, using the
const keyword before the type of the field.
- A constant variable should have value at design time.
- All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword "static".
- Constants are copied to all the dlls where is refereeing the parent class ie even if you change the the original constant value and recompile the parent dll , the other dll will still use the old value. The size of the executable goes up since all these constants are copied to the respective dlls
- Constant variables can be called with Class name only.
Readonly:
The
readonly keyword is a modifier that you can use on fields. When a field declaration includes a
readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
- We cannot modify the readonly values outside the constructor or variable initializer.
I think the following example program helps you to find the differences between Constant and Readonly
class MyClass
{
public int x;
public int y;
public const int c1=100;
public readonly int c2;//c2=some value is also acceptable..
public MyClass(int p1, int p2)
{
x = p1;
y = p2;
// c1 = p1 + p2; Generates error because we can't modify the constant variables...
c2 = p1 + p2;
c2 = c2 + 100; // some changes to readonly for better understanding...
//c1= 10; then error occurs...
}
public void modify()
{
//c2 = c2 + 200; Error :: A readonly field cannot be assigned to (except in a constructor or a variable initializer)
Console.WriteLine("c2 value after trying to modify:"+c2 );
}
}
class program
{
public static void Main()
{
MyClass obj = new MyClass(11, 22);
obj.x = 155; //acceptable bcz normal variable...
//obj.c2 = 55; generates an error this is the use of readonly...After creating the instance we cannot modify the readonly variables...
Console.WriteLine("x = {0}, y = {1}", obj.x, obj.y);
Console.WriteLine("c1 = {0}, c2 = {1}", MyClass .c1, obj.c2);//calling const c1 with its class name...and Readonly with Object Name.
Console.ReadLine();
}
}
// Constant variables can be initialized at the time of declaration only whereas readonly initialized At declaration or any where.
// Constant variables can be called with class name only...but readonly can be called with object name only...
Output:
x = 155, y = 22 c1 = 100, c2 = 133
c2 value after trying to modify :133
|
No comments:
Post a Comment