Wednesday, September 9, 2009

Const Vs Fields

Constant : constant is stored in module's metadata after compilation, so it cannot change at the runtime .

E.g :

10 const int i = 9;

Note : Only primitive types(int,boolean,char etc ) can be Constants.Then the compiler takes const as literal(The value is hardcode in source code ) as shown below.

Fields: Are dynamic memory allocation, so value can be allocated at runtime only.

E.g :

10 static readonly int i = 9;

Readonly – fields can be written only with in constructor method.

Note: No need to be primitive type and it support both static and non-static fields

Note : Any datatype the compiler directly supports are called primitive datatype .

E.g : in C# an int maps directly to a System.Int32