Using const in a method

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 using const use any benefit than just declaring a string as a string? Is this not interned?

+5
source share
3 answers

True, in both cases he will be interned.

By marking it as const, your meaning becomes clear do not touch this string variable, do not assign a different value to it.

+4
source

Here's how your last code would look in 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 will be microscopic.

+1
source

There are several reasons why declaring a const constant. First of all, he tells anyone who reads the code that the value will remain unchanged, that the udentifier is just an alias for the value. Secondly, the optimizer will have an easier task to find out if the identifier value can change between two readings. Declaring this value makes it very simple, because it cannot change. For me, the old reason is more important. Writing code that clearly shows intent is one of the developer’s most important habits.

+1
source

All Articles