Static vs Readonly vs Const

Const

Characteristics:

  1. It is compile time. (Because at declaration you have to assign value to it, otherwise it will give you error).
  2. Can be initialized only in declaration.
  3. Can create const variables within methods.
  4. Cannot declare const properties, methods, events.
  5. User defined types i.e. class, structs & arrays cannot be const.
  6. Cannot use static keyword when declaring const. (Because: By default a constant is static, so you can't define them static from your side.)

Readonly

Characteristics:

  1. It is a runtime constant. (Because: Based on constructor we can initialize its value).
  2. Can be initialized while declaration or within constructors.
  3. Cannot create readonly variable within methods.
  4. Cannot declare readonly properties, methods, events.
  5. User defined types i.e. class, structs & arrays can be readonly.
  6. Can use static keyword when declaring readonly variable.

Static

Characteristics:

  1. Can be used with classes, fields, methods, properties, operators, events, and constructors.
  2. Cannot use with indexers, finalizers, or types other than classes.
  3. If a class is static then all its members should be static. Otherwise it will give compile time error.

When to use what?

  1. If you know the value will never, ever, ever change for any reason, use const.
  2. If you're unsure of whether or not the value will change, but you don't want other classes or code to be able to change it, use readonly.
  3. If you need a field to be a property of a type, and not a property of an instance of that type, use static.
  4. A const value is also implicitly static.

Comments

Popular posts from this blog

C# Tutorial