Thursday, 19 February 2015

Difference Between Constant,ReadOnly,Readonly Static KeyWord

Const(constant) : Here value is constant but at compile time only , it is  must to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.

Note:Constants should be assigned a value at the time of the variable declaration and hence are known at compile time.


Hence, constants are immutable values 
We cannot change their values.

Constants can 
public, 
private, 
protected, 
internal, 
protected internal 

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            const string co = "abc";
            Console.WriteLine(co);
            Console.ReadKey();
        }
    }

}

Output:





Example


In, the above Example, when i am trying to assign the value to X, it it say Errors

Read Only 
Readonly: Whose value we can change during runtime or we can assign it at run time but only through the non-static constructor.

Note: We can assign value to it only throught Non Static Constructor only.



Explanation:

In the above Example:
I am assigning the value by using the constructor only (non static constructor)  for the (public  readonly int X1;)


Here readonly int X1 is not static , so we can assign the value to it. But, When i am trying to assign the value to the variable        (public static readonly int X = 10;) I am getting the following error.





Note:
1 When i try to initialize the value in the static constructor than It gives me an error. 
2 When i try to initialize in the method, It gives me an error.

Example 2:

Output: 10

Example:



output:


Remember
Constants:
It can be assigned values only at the time of declaration

Have to be accessed using "Classname.VariableName"

Compile Time

Run Time
It can be assigned values either at runtime or at the time of instance initialization via constructor

Read only variables have to be accessed using the "InstanceName.VariableName"

Run time.


Static ReadOnly: It value can be assigned at runtime or assigned at compile time and we can change at runtime. 

Note: But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.




Output:



No comments:

Post a Comment