Skip to main content

Posts

Showing posts with the label constants v/s read-only

What is difference between constants and read-only?

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Constant Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static. public const int X = 10; A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time. void Calculate(int Z) {   const int X = 10, X1 = 50;   const int Y = X + X1; //no error, since its evaluated a compile time   const int Y1 = X + Z; //gives error, since its evaluated at run time } You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null. const MyClass obj1 = null;//no error, since its ev...