Sunday, July 18, 2010

readonly preferance


C# has two versions of constants. They are compile timed 'const' and run timed 'readonly'. As named, const variables are replaced with the value of that constant in the object code. But readonly constants are evaluated at runtime; they are referenced with IL( Intermediate Language) generated variables not the value. Compile time constants can be used only for primitive types.

readonly for instance constants are used to store different values for each instance of a class type. Compile time const are static constants by definition
// compile time
public const int Millennium = 2000;

// run time
public static readonly int thisYear = 2010;

Advantage of using const over readonly is performance, where as readonly prefers the increased flexibility due to runtime compatability constants.

2 comments:

  1. Should the runtime readonly be a static variable or can it be declared in any scope? Are compile time constants, converted to static scope during compilation?

    ReplyDelete
  2. Good question Srini.

    In terms of compile time constant 'const', you can't set a constant to a class or structure. Becaz classes or structures are initialized at run time with the new keyword, and not at compile time. So,const is an implicit static by framework for making no longer tied to a specific object.

    But, runtime readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.

    ReplyDelete