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?
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With