Difference amongst Const, Readonly, Static keywords

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.

  1. It cannot be left blank.
  2. I will be static after compilation.
  3. It is a kind of validator.
  4. Const behaves like Static.
  5. Can be used in attributes
  6. The compiler performs some optimization by not declaring any stack space for the field.
  7. 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

  1. A static member cannot be referenced through an instance. Instead, it is referenced through the type name.
  2. It is not possible to use this to reference static methods or property assessors.
  3. Only one copy of static fields and events exists
  4. 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.
  5. It is declared when a static class in initiated or static construer called.

Public static int a = 10; // Initialize a static field

Ebook Download
View all
Learn
View all