views:

120

answers:

7

Hi,

Is there any benefit to declare a local variable as "const" if I know that I won't be chaning its value?

Thanks,

+3  A: 

Yes. You will protect your code from accidentally changing this variable.

Developer Art
+1  A: 

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.

Jake Pearson
+2  A: 

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)

Spooks
+1  A: 

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.

Paul Hadfield
I declare local consts for other programmers more than any other reason.
Ryan Bennett
A: 

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

abatishchev
+2  A: 

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

JLWarlow
+1  A: 

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.

Dan Bryant
I like this Dan. I've noticed that MS seem to do this in their source code:base.Compute(10, true /* includeFoo */);which has the benefit of remaining one line.
Nik
In C# 4.0, you can use named parameters to accomplish the same thing (hopefully the parameters have sensible names!) Not what they were introduced for, but they have the advantage of ensuring you use the correct names (using either const locals or comments in a call with many such flags might get them accidentally muddled).
shambulator
When I design my own interfaces, I tend now to try to avoid boolean parameters in the first place and either create different public methods that map to an internal method with a flag or use enum values for the flag. I still find this technique helpful when interoperating with APIs that take a boolean or 'magic' parameters (like string.Empty to indicate 'missing').
Dan Bryant