#338 – Static Readonly Fields vs. Constants

A static readonly field in a class is very similar to a constant.  Both expose a constant, static value that is associated with the class, independent of any instances of the class.

We could declare a static readonly field in a Dog class:

        public static readonly string TheDogMotto = "Man's Best Friend";

We could also declare this value as a constant:

        public const string TheDogMotto = "Man's Best Friend";

The value of a constant must be known at compile-time and specified as part of the declaration.

The value of a static readonly field is set at run-time, so it can be different from run to run.  It is specified in either the declaration or within a static constructor.

Use a readonly field for values that you won’t know until run-time or have to calculate.  Use a constant for values that are known and never change.


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #338 – Static Readonly Fields vs. Constants

  1. Pingback: #603 – Using Constants Can Force Recompilation « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: