Tuesday, May 4, 2010

Constant Vs ReadOnly in C#, which is faster & better to use?

Difference between:  Constant Vs ReadOnly in C#, with a practical scenario in .Net projects.

Ans:
1. constant has to be assigned at the time of declaration.
    readonly can be assigned (only) in the constructor.

2. constants are implicitly static. Cant declared as static.
    readonly can be declared as static;
For eg:         private static readonly ILoggingService loggingService = LoggingServiceFactory.GetService(typeof(Class Name));

3) Constants are bonded at compile time (=>Faster) , where as value substitution in case of readonly happens at runtime (=>Slower) .
   
Case Study:
Suppose I have a constant defined in an Assembly(AS) & using it in another Assembly(AD).
After compilation,
Incase of constant it will replace the original string in the IL code, where as in case of read only in IL code still the readonly variable will be present.
Suppose you have changed the constant value in the source assembly, it wont reflect until you compile the destination assembly. :-(

So better to use readonly as static variable though a little bit compromise we have to bear in terms of performance.

Monday, May 3, 2010

COCKROACH " STORY : Good one, Must read it..

This is really a wonderful article; If letters are not visible, u can copy it & save as jpg file on ur desktop & read by zooming it :-).  

Hope this is going to add some change in our life & how we are responding the situations!!!