Monday, December 20, 2010

Const vs ReadOnly Property

Const
1. It is defined at the compile time and cannot be changes at runtime.
2. Constant are declared as a field, using the const keyword and must be initialized as they are declared.
3. Const value cannot be changed in anywhere in the application else it'll cause a compiler error.
4. Const must be value type, an enumeration, a string literal or a refrence.
5 Since classes or structures are initialized at run time with the new keyword, and not at compile time, we can't set a constant to a class or structure.
6. Constants can be marked as public, private, protected, internal, or protected internal.
7. Constant can be accessed directly by class name like static variables.

public class MyClass
{
public const double xyz=2;
}


Static Read Only Property
1. Readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.
2. Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used.
3. Readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
4. A readonly member can hold a complex object by using the new keyword at initialization.

public class MyClass
{
public readonly double PI;
public MyClass()
{
PI = 3.14159;
}
}

No comments:

Post a Comment