Const versus Readonly

by Sottje 22. February 2010 21:43

Developers often make use of constants to hold static values to use through the class or even through the application.
Sometimes we use de const and sometimes the static readonly. They seem to do the same but aware of the differences.

Const
The const field is a defined and evaluated at compile time and cannot be changed at runtime.
So therefore a const member can only be of a value type, an enumeration a string literal or null.
The initialization of classes and structures is done at runtime with the new keyword os cannot be used with const.

It behaves like a static member but cannot be decalered like one.

public const string OwnerName = "Sottje";

Readonly
The value of a readonly fields can be initialized at runtime by declaration of using the constructor.
When having multiple constructors, readonly fields have different values.
A readonly member is not static by default. Make it explicit by using the static keyword.

public readonly string OwnerName = "Sottje";

or

public class MyClass 
{ 
     public readonly string OwnerName; 

     public MyClass() 
     { 
          OwnerName = "Sottje"; 
     } 
}

Tags: , ,

Professional | c#