C# Constants – Difference Between Const and Static

c++constantsstatic

I am eager to know the difference between a const variable and a static variable.

Is a const variable also always static? What is the difference between them?

Best Answer

const fields can only hold value types or System.String. They must be immutable and resolvable at compile-time.

static readonly fields can and generally do hold reference types, which (other than strings) can only be created at runtime. These can (but shouldn't) be mutable types; the only thing that cannot change is the reference itself.

If you need to maintain a "constant" set of instances that are reference types, you generally do it with a set of public static readonly fields, such as the members of System.Drawing.SystemColors.

Last but not least, initialization of a readonly field can be deferred until the execution of a constructor, which means that it even though it can only be written to once, it does not always have to be initialized with the exact same value. True constants declared with const can only ever have a single value (specified at compile time).