Constant VS ReadOnly

Constant

Constant is an immutable value which is known at the time of compilation and the value of constant does not change for the life of application or program.
 
const int testInt = 10;
const string testString = "This is Test String";
 
User define types including class, array or structure cannot be constant. C# does not support Constant method, event and properties. We can mark constant as public protected, internal, protected internal and private.
The Static modifier cannot be used with Constant. A constant is able to participate only with the constant expression. For example
const int int1 = 500;
const int int2 = int1 + 300;
int runtimeInt;
const
int int3 = int2 + runtimeInt; // this will give compile time exception
 

Read only

A read only field can be initialized either at the time of the declaration or with in the contractor of the same class, for example
public class MyReadOnlyTest
{
          public readonly int readOnlyInt = 5;
          public readonly string readOnlyString;
          public MyReadOnlyTest()
          {
                   readOnlyString = "This is readonly string";
           }
}
 
We can also specify a read only field as a static.
public static readonly int readOnlyInt = 15;
 
Readonly can also be applied to a value type as well as a reference type like class.

Constant VS Read only

Constant

Read only

Constant field can only be initialized at the time of declaration.

Readonly field can be initialized at the time of declaration as well as with in the constructor of same class.

Constant is compile time constant.

Readonly is runtime constant

We cannot use static modifier with Constant.

We can use Static modifier with ReadOnly field.

Constant field of a reference type other than string can only be initialized with null only.

The readonly field is able to hold complex object like class by using new keyword for initialization.

Constant Fields are implicitly static.

Readonly Fields are not implicitly static.

 
 
Ebook Download
View all
Learn
View all