But you can find A different, far more subtle difference that we must always know about. If a const variable exists in Assembly A and is also used in Assembly B, when Assembly A receives recompiled that has a new worth for your const variable Assembly B will still provide the preceding
Meta Stack Overflow your communities Sign up or log in to personalize your checklist. additional stack Trade communities firm blog
In the beginning look this Appears lots similar to a constant area, since a constant can only be provided a worth at its declaration and can't have that value modified any where else. The real difference lies in the main points.
With readonly you might be telling the clr that the worth will never change in the course of the life span on the occasion or the AppDomain in the case of the static field and so it can be lazy and utilised cached values securely.
C99 borrowed the usage of const from C++. Conversely, static continues to be the supply of lots of debates (in the two languages) as a consequence of its frequently baffling semantics.
And we will assign non-primitive types to null to determine a const.But it really’s worthless to declare read more a const reference sort which is assigned to null.
Use const when the worth is complete constant that received’t change more than time. As an example Range of days in each week is 7. This is usually constant. and when in doubt use static readonly to stay away from the dll versioning trouble.
Just very last week I had a completely new-to-ASP.Web developer (we will contact him Roger) talk to me to elucidate what the main difference was in between a variable declared as const variable and that very same variable declared as static readonly.
Constant variables however are prevented from altering. A typical utilization of const and static collectively is in just a course definition to deliver some type of constant. class myClass
course S mutable static int i; // err mutable static int j; // err static int k; // ok, all cases share the same member
up vote 0 down vote Uncomplicated and shorter answer is memory is allocated for static and const only once. But in const which is for only one price wherever as in static values may well improve but the memory region remains the identical until finally the tip of This system.
Now we get again towards the dilemma Roger initially questioned: what's the distinction between a variable declared as const and the identical variable declared as static readonly?
user266117 4615 insert a comment