Clearly, declaring a local variable as const
, prevents runtime modification. Const
instance variables are static (I believe). Does this have any bearing on the nature and use of const
local variables? (e.g. threading)
views:
142answers:
5Since every method call creates its own stack area and therefore owns its own local variables, you won't need to worry about locals beeing modified from other threads.
AFAIK creating locals as const in c# won't create any variable or field at all, but instead the assigned constant value will be placed inline everywhere you use it inside the method.
A const
is not a variable, that's why it's called a constant.
"const" variables have to have a primitive type (e.g. int, bool). Whenever a "const" variable appears in the source code (whether it's local or global), this instance is replaced with the const value itself. So:
const int foo = 42;
return foo + 69;
after optimizing becomes:
return 42 + 69
or rather:
return 111;
There are no threading issues because const variables have primitive types and they only exist at compile time.
The main advantage of locally using const
is so you don't accidentaly set the identifier to another value which may change the correctness of your code.
A constant is not a variable, and it isn't actually stored anywhere. As it isn't stored, it's not an instance member, and it's not static.
The constant is just a name for a value. When the code is compiled the value is inserted where the constant is used. (This has implications if you use a constant declared in a different assembly. Changing the declared value of the constant doesn't change the value used until you recompile the code that uses the constant.)
So, a constant declared locally works exactly as a constant declared anywhere else, it's only the scope that differs.