Home » C# scripts » Difference between const and readonly in c#

Difference between const and readonly in c#

const: It is must to assign a value to that variable and you cannot change it again and again in the program. It is implicitly static and allows you to access it through class name.

ex:  public class abc
     {
     const string myName ="Kate";
     public abc()
     {
      myName ="John"; // This will give compile time error
     }
     }
 ReadOnly: It allows us to assign value during runtime. Please note that you can assign a value only through non-static constructor.

ex:  public class abc
     {
     readonly string myName ="Kate";
     public abc()
     {
      myName ="John"; // This will run successfully
     }
     }

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *