The difference is that the value of the readonly static field is set at run time and therefore can be changed using the containing class, while the value of the constant field is set to a compile time constant.
In the static readonly case, the contained class is only allowed to modify it
in a variable declaration (via a variable initializer) in a static constructor (instance constructors if they are not static) static readonly is usually used if the field type is not allowed in the const declaration or when the value is unknown at compile time.
Readonly instance fields are also available.
Remember that for reference types in both cases (static and instance), the readonly modifier only prevents you from assigning a new link to this field. It does not specifically make the object referenced by it immutable.
class Program { public static readonly Test test = new Test(); static void Main(string[] args) { test.Name = "Program"; test = new Test();
The difference is that read-only static access can be changed using the containing class, but the constant can never be changed and must be initialized until the compile time constant. To expand in the static case a read-only bit, the containing class can only change it:
- in the variable declaration (via the variable initializer).
- in a static constructor (instance constructors, if it is not static).
Keyword Const in C # .NET
Example: public const string abc = "xyz"; It is initialized only at the announcement. The value is evaluated at compile time and cannot be changed at run time. Attempting to change it will cause a compilation error. Constants are already static. Since classes and structures are initialized at run time with the new keyword, you cannot set a constant to a class or structure. But it must be one of the integral types. Readonly keyword in C # .NET
Example: public readonly string abc; It can be initialized in the declaration code or in the consturctor code. The value is evaluated at runtime. May be declared as static or instance level attribute. A read-only field can contain a complex object using the new keyword at run time.
Rakesh Kumar Jaiswal Apr 03 '09 at 8:55 2009-04-03 08:55
source share