Difference amongst Const, Readonly, Static keywords
Const: It a design time mythology. It's represent the property of class.
If you assign a value to const variable and value of const variable will never
change over time. Following points must be remembered about const keyword.
- It cannot be left blank.
- I will be static after compilation.
- It is a kind of validator.
- Const behaves like Static.
- Can be used in attributes
- The compiler performs some optimization by not declaring any stack space
for the field.
- Constants can be marked as public, private, protected, internal, or
protected internal.
public const double pi = 3.14; // Compile time constant
Readonly: Readonly keyword you can use in variable declaration. 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.
For an instance field, instance constructor of the class contains the field
declaration. For static field, static constructor of the class contains the
field declaration.
public readonly int a = 10; // Initialize a readonly field
public AnyClass()
{
a = 20; // Initialize a readonly instance field
}
Public static readonly int a = 10; // Initialize a static field
static AnyClass()
{
a = 20; // Initialize a readonly static field
}
Static: Static keyword use to declare the static variable which belongs
to the type itself rather than to specific objects. The static modifier can be
used with fields, methods, properties, operators, events and constructors, but
cannot be used with indexers, destructors, or types.
Following points must be remembered about Static keyword
- A static member cannot be referenced through an instance. Instead, it is
referenced through the type name.
- It is not possible to use this to reference static methods or property
assessors.
- Only one copy of static fields and events exists
- The static modifier can be used with classes, fields, methods,
properties, operators, events and constructors, but cannot be used with
indexers, destructors, or types other than classes.
- It is declared when a static class in initiated or static construer
called.
Public static int a = 10; // Initialize a static field