开发者

Is there any benefit to declare a constant in a local scope in C#?

Is there any benefit to declare a local variable as "const" if I know that I won't be chaning its v开发者_如何学编程alue?

Thanks,


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)


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

Edit: Reply to "constant propagation" as the comments box has size limit

Using ildasm to check betweeen const and none const for release with optimisation:

The code

int test = 4;
Console.WriteLine(test*2);

Compiles to

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       11 (0xb)
  .maxstack  2
  .locals init ([0] int32 test)
  IL_0000:  ldc.i4.4
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  ldc.i4.2
  IL_0004:  mul
  IL_0005:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_000a:  ret
} // end of method Program::Main

While

const int test = 4;
Console.WriteLine(test*2);

gets optimised to

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldc.i4.8
  IL_0001:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_0006:  ret
} // end of method Program::Main

This is using 2010 in release with optimisations.

I did a search to learn more about constant propagation and while posible, the current compiler doesn't do this as mentioned here


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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜