C# |
|
There are two related features: const and readonly. Both of them are used as modificators of teh variable declaration.
The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable cannot be modified:
class Test
{
public const double pi = 3.14159265359;
public const string URL = "http://www.greatis.com";
void Foo()
{
const int x = 1;
}
};
The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class:
class Test
{
public readonly int y = 25; // Initialize a readonly field
public Test()
{
y = 24; // Initialize a readonly instance field
}
}
The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants:
class Test
{
public readonly int y = 25; // Initialize a readonly field
public const int z = 30; // Initialize a const field
public Test()
{
// y = 25; // default value
}
public Test(int var)
{
y = var; // OK, initialize a readonly field
z = var; // Error can't initialize const field
}
}
|
|
|
|
|
|
Fields can be declarated as readonly. This keyword allows to modify variable value in constructor of the class. |
|
|
|
|
|
|
|
|
|