1
Reply

Difference between constant and readonly c# ?

Rohan Gupta

Rohan Gupta

9y
445
0
Reply

    Constants:Constants are declared using a "const" keyword.Constants should be assigned a value at the time of the variable declaration and hence are known at compile time.example :void add(int Z) {const int X = 10, X1 = 50;const int Y = X + X1; //no error, since its evaluated a compile timeconst int Y1 = X + Z; //gives error, since its evaluated at run time }Readonly variables are known at runtime, they can be assigned a value either at runtime or at the time of the instance initialization or with in the constructor of same class. class MyClass {readonly int X = 10; // initialized at the time of declarationreadonly int X1;public MyClass(int x1){X1 = x1; // initialized at run time} }