Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of const in a method

Tags:

c#

.net

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?

like image 445
James Hughes Avatar asked Mar 13 '10 15:03

James Hughes


People also ask

When should a method be const?

A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.

What does it mean for a method to be const?

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.

What is the benefit of const?

Here are some of the advantages of using const: Using const helps avoid polluting our global object with unnecessary properties. Using const helps avoid hidden bug updates, such as modifying a constant value by mistake, updating wrong variables which are in different scope block but declared with same name, etc.


2 Answers

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.

like image 51
Oded Avatar answered Oct 21 '22 17:10

Oded


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.

like image 33
Darin Dimitrov Avatar answered Oct 21 '22 16:10

Darin Dimitrov