Wednesday, April 20, 2011

Beware of Constants


Let say I have a third party library having code as following

namespace Test
{
    public class TestClass
    {
        public const string NAME = "Abhishek Tiwari";
    }
}

My application uses this library and prints this name on console in following manner

internal class Program   
{        
      private static void Main(string[] args)        
       {             
          Console.WriteLine(Test.TestClass.NAME);             
          Console.ReadLine();         
       }    
}

After sometime my library provider company is owned by some other company and changes the const value to something public const string NAME = "I am no more Abhishek Tiwari";

Now as being a loyal customer to that company, you get  the new version of the library and replace the old version by it and now click on your executable again.

Whack!!! You still see "Abhishek Tiwari" written on the console. 

So what happened in the background is mystery for you but before you bang your head here and there in confusion, let me solve this puzzle for you. 

Actually when you last built your project, your compiler has put the hard-coded values in place of consts everywhere in your IL so those consts values no more refer to any part of the code whatsoever. If you look into the IL, you will find something like

//My IL (compiled code)
internal class Program   
{        
      private static void Main(string[] args)        
       {             
          Console.WriteLine("Abhishek Tiwari");             
          Console.ReadLine();         
       }    
}

So even if now I have updated the third party without rebuilding my code (since it is essentially not required) my IL will remain same, and in my IL const "NAME" which was linked to third party is vanished, leaving hard coded const value behind.


Get working code from TestConst

I hope if you are a third party provider, you will keep this in mind to avoid any shock. I am not sure what is the best possible solution for this (will keep you posted, if I come across any) but for now you can change your "const" type by "static readonly" so that your library consumer can always see the modifications.



** Thanks to Shailendra (Author in aspnettechstuffs) for sharing this valuable information with me.



No comments:

Post a Comment