Author : MD TAREQ HASSAN | Updated : 2021/03/22
Readonly
Readonly variable can be assigned only once (declaration time, in constructor or in static constructor)
public readonly int y = 5;
class Foo
{
readonly int bar;
Foo(int bar)
{
this.bar = bar;
}
}
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 assigned multiple times in the field declaration and in any 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 as in the following example:
public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
Constant
- Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type.
- You do not use the static keyword to declare them
- Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant
static class Constants
{
public const double Pi = 3.14159; // no need to use static keyword
}
var area = Constants.Pi * (radius * radius);