HI WELCOME TO KANSIRIS

Difference between Const & ReadOnly

Leave a Comment
Constant (const) and Readonly (readonly) both looks like same as per the uses but they have some differences:

Constant is known as “const” keyword in C# which is also known immutable values which are known at compile time and do not change their values at run time like in any function or constructor for the life of application till the application is running.

Readonly is known as “readonly” keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. You can assay their value by constructor when we call constructor with “new” keyword.

See the example-



So finally remove that line of code from class and call this Check() function like the following code snippet:

1.         class Program {
2.         static void Main(string[] args) {
3.         Test obj = new Test();
4.         obj.Check();
5.         Console.ReadLine();
6.         }
7.         }
8.         class Test {
9.         readonly int read = 10;
10.       const int cons = 10;
11.       public Test() {
12.       read = 100;
13.       }
14.       public void Check() {
15.       Console.WriteLine("Read only : {0}", read);
16.       Console.WriteLine("const : {0}", cons);
17.       }
18.       }

Output:




 Constants:
1. Constants can be assigned values only at the time of declaration
2. Constant variables have to be accessed using "Classname.VariableName"
3. Constants are known at compile time
Read Only:
1. Read only variables can be assigned values either at runtime or at the time of instance initialization via constructor
2. Read only variables have to be accessed using the "InstanceName.VariableName"
3. Read only variables are known at run time.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.