What’s the difference between const and readonly?
Nipun Tomar
1)Constant variable means it assigned the value at declaration time only. 2)It is like a MACRO.you can use const variable throught the application 3)In Readonly variable you can assign a value at declaration time or in constructor also.It means readonly variable can have multiple value per applications.
Const and ReadOnly are the keywords in .Net and solve the same purpose that of keeping a value unaltered through object's lifetime.Whereas below are the differences--Const is used whenevr --:1) a value is known prior to runtime.2) value can be assigned to a constant anywhere through out the programReadOnly is used whenever --:1) a value is not known until the runtime.2) If there are any computations are to be done on the value.3)Readonly value can only be assgned within the constructure.
When using the const keyword to set a constant variable, the value needs to be set at compile time. The const keyword may not be used with an object of reference type.In case a reference type needs to be assigned a non-changeable value, it may be set as readonly
The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable.