Difference between Constant, Readonly and Static in C#

Constants:

  • Classes and structs can declare constants as members.
  • Constant fields or variables must be assigned a value at the time of declaration and after that they cannot be modified.
  • By default constant is static and we cannot change the value of a const variable throughout the entire program.
  • Constants can be marked as public, private, protected, internal, or protected internal access modifiers.

Readonly:

  • The readonly keyword is a modifier, which we can use on fields.
  • A readonly field can be initialized either at the time of declaration or with in the constructor of same class.
  • We can change readonly field value during runtime or we can assign it at run time but only through the non-static constructor.

Static:

  • The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
  • If the static keyword is applied to a class, all the members of the class must be static and Static methods can only access static members of same class.
  • Static properties are used to get or set the value of static fields of a class.
  • Static constructor can’t be parametrized. Access modifiers can not be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.

 

Leave a Reply