+ 1

So why would I ever use const instead of readonly?

8th May 2016, 12:27 PM
Martin M. Klöckener
Martin M. Klöckener - avatar
2 Respuestas
+ 5
Constants are way faster than readonly fields. So, you should choose const over readonly, if you are able to do that. If your value is constant and you are in complete control of the program, const is better. For instance, in DLLs. When you use a const field or declaration, the C# compiler actually embeds the const variable's value directly in the IL code. Therefore, it essentially erases the const as a separate entity.
26th May 2016, 1:19 PM
James Flanders
+ 1
Small difference between Constants and ReadOnly is very important; constant have to be initialized when you declare it and you cannot change its value ever, but readonly is not mandatory to initialize it when declaration and you can change its value just using constructor of your class.
7th Jan 2017, 5:00 AM
Ahmad Hamdan
Ahmad Hamdan - avatar