Tom Fischer

  Home  |   Contact  |   Syndication    |   Login
  21 Posts | 0 Stories | 44 Comments | 0 Trackbacks

News

Archives

Post Categories

.NET Framwork

TFS

Tools

Visual Studio

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!

posted on Tuesday, August 26, 2008 1:55 PM

Feedback

# re: The big side affect of const versa readonly 8/26/2008 8:08 PM rustycoslett
I didn't even know there was a readonly keyword! Sounds kind of like using Optional in VB.NET and consuming in another assembly.

Compiler baked in goodness.

rusty

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: