开发者

Using local const

I installed resharper and it suggested to me that I should modify some local variables to a const. I never heard of this, so I starting googling. MSDN sure开发者_如何学JAVA enough has a bit of code of having local consts, but no explanation why. On stackoverflow I came across questions but had more to do with whether having a local const is faster than not having them.

So, I'm scratching my head here. Why is it possible to have a local const? Does it have to do with semantics? Is there some benefit? Maybe both?


Const have a main benefit: it's value is unchangeable and this enforce code stability and solidness.

Let's say you've to define some date format during some method execution and it's valid for this one only. Why don't you'd be using a constant?

public void SomeMethod()
{
    const string dateFormat = "MM/dd/yyyy";

    ... // Lot of operations


    return Date.Now.ToString(dateFormat);
}

You avoid human errors if you use constants if it's possible to use them.


Having a local const is simply a matter of scoping. Instead of the const being available to the entire class or consumers of that class (if the const is public) it is only available in the method where you declare it.

To demonstrate why ReSharper suggest the refactoring I have included the generated IL for a simple example.

Without const:

string s = "foo";
Console.WriteLine(s);

Generated IL:

ldstr       "foo"
stloc.0     
ldloc.0     
call        System.Console.WriteLine

With const:

const string s = "foo";
Console.WriteLine(s);

Generated IL:

ldstr       "foo"
call        System.Console.WriteLine
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜