#603 – Using Constants Can Force Recompilation

Here’s an additional difference between a static readonly field and a constant.  Let’s say that you have a class that includes both a public static readonly field and a public constant.

public static readonly string ReadonlyMotto = "Man's Best Friend";
public const string ConstantMotto = "Man's Best Friend";

Now assume that you have two assemblies, as follows.

At this point, let’s say that you want to change the two elements that contain the dog mottos, i.e. the readonly field and the constant.  So you change the values and re-compile Dog.dll but do not re-compile DogViewer.exe.

At this point, something interesting happens at runtime if you run DogViewer.exe.

  • DogViewer sees the new value of the readonly field
  • DogViewer does not see the new value of the constant

This happens because when you compile code that uses a constant, the value of the constant is included in the generated code.

Advertisements

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 #603 – Using Constants Can Force Recompilation

  1. Steven says:

    Good to know. Thanks, Sean!

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: