tags:

views:

83

answers:

3

In the following method,

public void InspectList(IList<int> values)
{
    if(values != null)
    {
        const string format = "Element At {0}";
        foreach(int i in values)
        {
            Log(string.Format(format, i));
        }
    }   
}

Does the use of const provide any benefit over just declaring the string as a string? Woudl it not be interned anyway?

+4  A: 

True, in both cases it will be interned.

Marking it as a const makes your meaning clearer - do not touch this string variable, do not assign a different value to it.

Oded
+1  A: 

Here's how your final code will look like in the two cases:

  • Using const:

    public void InspectList(IList<int> values)
    {
        if(values != null)
        {
            foreach(int i in values)
            {
                Log(string.Format("Element At {0}", i));
            }
        }   
    }
    
  • Without const:

    public void InspectList(IList<int> values)
    {
        if(values != null)
        {
            string format = "Element At {0}";
            foreach(int i in values)
            {
                Log(string.Format(format, i));
            }
        }   
    }
    

So in the second case you will have an additional local variable declared, but IMHO the difference would be microscopic.

Darin Dimitrov
That would depend on the optimizer. Im Guessing that the current MS C# compiler Will yield a result similar to yours but im unsure about any differences in the resulting binary code after the IL code has been compiled
Rune FS
+1  A: 

There's multiple reasons why declaring something that is a constant as const. First of all it tells any one Reading the code that the value Will stay the same, that the udentifier is simply an alias for the value. Secondly an optimizer would have an easier job figuring out if the value of an identifier could have changed between two reads. Declaring it cost makes that very easy since it can't change. To me the former reason is the more important. Writing code that clearly show the intention is to me one of the most important habits a developer could have.

Rune FS