Saturday, May 5, 2018

C#: What is the difference between constant and read only in c#

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

We have a Test Class in which we have two variables one is readonly and another is constant.
  1. class Test {  
  2.     readonly int read = 10;  
  3.     const int cons = 10;  
  4.     public Test() {  
  5.         read = 100;  
  6.         cons = 100;  
  7.     }  
  8.     public void Check() {  
  9.         Console.WriteLine("Read only : {0}", read);  
  10.         Console.WriteLine("const : {0}", cons);  
  11.     }  
  12. }  
Here I was trying to change the value of both the variables in constructor but when I am trying to change the constant it gives an error to change their value in that block which have to call at run time.

ASP.NET

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:ASP.NET

No comments:

Post a Comment