The big side affect of const vs. readonly.... Back into C#!
After spending a couple of days at DevLink (which I really enjoyed) I am back in C# code.
I just stumbled over a very interesting fact, which I knew that there is an important difference but was not aware of some interesting side affect. It was an eye-opener, so I thought I have to share this one with you. If you already know this - good for you :-)
The big side affect of const vs. readonly:
First some theory (I guess most of you already know it - but just for the record):
- const expression get replaced at compile time with the actual value.
- If you reference a DLL with a const the value of the const gets written into your dll at compile time
- const can only be used for numbers strings and apparently structs
- readonly gets assigned at runtime.
- readonly can be set only in the constructor or direct reference
So lets look at a small example:
In an separate assembly (e.g. Infrastructure) you define
public class MyConst
{
public static readonly int Start = 0;
public const int End = 15;
}
In a different project you use:
for (int i = MyConst.Start; i < MyConst.End; i++)
{
Console.WriteLine("i={0}", i);
}
The expected output is:
i=0
..
i=14
So now we change the value in our seperate Assembly to:
public class MyConst
{
public static readonly int Start = 100;
public const int End = 115;
}
Because we did not change our actual project we only deploy our seperate assembly and run it again....
And nothing happens... The loops does not even start ...Ooops
Why? We already gave the answer in the theory section:
- During compile time the compiler replaces End with 15 and not a reference to the actual object.
So simple and mind-blowing!
I hope you also enjoyed this one with me
Tom
P.S.: This one is for you Ian!