Numerous books and articles explain the difference between
public const string Foo = "foo";
and
public static readonly string Foo = "foo";
The former is treated as true constant that never ever changes, and it may be baked verbatim into the code of any caller:
const string CarthageFate = "Carthago delenda est";
The latter is treated as a field that might actually change between assembly versions, program invocations, or even in different app domains. You can actually do things like
public static readonly string InitTime = DateTime.Now.ToString();
So, I read about all that, but I never tested it. Until now that is. Since this fact was material for my current project, I wrote a little test that I offer for you enjoyment: StringConstant.zip.
We have two versions of a DefiningLib
library defining some constants and readonly fields, and a UsingApp
that uses it.
public const string VersionConst = "v1"; public static readonly string VersionField = "v1"; public static readonly string InitTime = DateTime.Now.ToString();
Version 1 is compiled by the standard “Debug” configuration and produces the following output:
DefiningLib version: 1.0.0.0 Init time: 1/11/2013 9:51:38 AM VersionConst: v1 Versionfield: v1
Then we compile version 2 of the defining lib by switching to “Debug.v2” solution configuration. Version 2 looks like this:
public const string VersionConst = "v2"; public static readonly string VersionField = "v2"; public static readonly string InitTime = DateTime.Now.ToString();
Only DefiningLib
changes, UsingApp
stays the same. We then manually copy DefiningLib.dll
from DefiningLib\bin\Debug.v2
folder to UsingApp\bin\Debug
and invoke UsingApp.exe
. The output is as follows:
DefiningLib version: 2.0.0.0 Init time: 1/11/2013 9:54:06 AM VersionConst: v1 Versionfield: v2
Voila, the theory is indeed right. The constant was baked in into UsingApp.exe
and stayed “v1”. The field reference was updated to “v2” as expected.
Lesson learned: if there is even a remote possibility that your “constant” value might change in the next version, make it a readonly field.
Permalink
Great blog Ivan! My name is Anna Holland, and I am a Marketing Coordinator at Syncfusion. I am reaching out to see if you would blog about one of our free e-books, collectively known as the Succinctly series. It is a great way to add value to your personal website. There are many topics to choose from; you can check out our complete list of books at http://www.syncfusion.com/resources/techportal/ebooks. They are written by talented experts who are personally selected by Syncfusion. Our goal for each book is to take 500+ pages of information on a topic such as ASP.NET MVC, jQuery, HTTP, etc., and condense it to about 100 pages of essentials. If you choose to blog about one of our e-books, products, or any other Syncfusion resource, you will receive a free $20 Amazon gift card. Please let me know if you have any questions. Thank you for your time, and I look forward to hearing from you!