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.
No comments:
Post a Comment