C# Difference Between Const and Readonly

Below is the list of differences between these 2 Type Qualifiers:

Const:

  1. Can't be used “with” static keyword because they are implicitly static. You can get the const value without creating an instance of the containing class just by the use of class name.
  2. Value is evaluated at compile time, cannot be changed at runtime. Initiailized at declaration only. It can only be set to a known value at compile time.
  3. Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.
Readonly:
  1. Can be either instance-level or static. Readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly.
  2. Can be initialized at runtime in declaration or by code in the constructor. You could read in a value for a readonly variable from a config file or set its value based on some other parameter that is known at runtime.
  3. A readonly member can hold a complex object by using the new keyword at initialization.

Hope this helps someone.

Good luck,
Serdar.

Leave a Reply

Your email address will not be published. Required fields are marked *