Hi,
Is there any benefit to declare a local variable as "const" if I know that I won't be chaning its value?
Thanks,
Hi,
Is there any benefit to declare a local variable as "const" if I know that I won't be chaning its value?
Thanks,
Yes. You will protect your code from accidentally changing this variable.
Declaring the local as const will let the compiler know you intention so you won't be able to change the value of your variable elsewhere in your function.
You would usually use a const throughout your entire solution. But the benefits for using in a local scope, would be that you know some place else in your scope you won't be changing it. And also if someone else is working on this code, they will know not to change it as well. This makes your program more maintainable, because you need to maintain only the const (even if its just in a local scope)
Further to the valid answers, not only do you tell the compiler that the value won't be changing, you quickly tell anyone else that will be looking at your code.
Depending on case of use..
For example,
void Foo()
{
const string xpath = "//pattern/node";
new XmlDocument().SelectNodes(xpath);
}
in this case I think const declaration is meaningless
Declaring the variable const will also allow the compiler to do optimisation - instead of say allocating an int on the stack and placing its value there, the compiler may just use the value directly with your code
ie The following:
const int test = 4;
DoSomething(test);
Could be compiled as
DoSomething(4);
by the compiler
I like to do this when I'm passing a boolean flag indicator to a method:
const bool includeFoo = true;
int result = bar.Compute(10, includeFoo);
This is more readable for me than a simple true/false, which requires reading the method declaration to determine the meaning.