Skip to main content

String.Format can be used

In This Article

CodeRush Classic shows the String.Format can be used code issue if a string concatenation expression includes more then two terms.

#Fix

Use a String.Format() call instead of the string concatenation expression.

#Purpose

Highlights the string concatenation expressions, which should be replaced with a String.Format() call to improve code readability.

#Example

public string GenerateFileName(string fileName, string extension)
{
    string newName = fileName + "." + extension;
    int i = 0;
    while (File.Exists(newName))
    {
        newName = fileName + i + "." + extension;
        i++;
    }
    return newName;
}

Fix:

public string GenerateFileName(string fileName, string extension)
{
    string newName = String.Format("{0}.{1}", fileName, extension);
    int i = 0;
    while (File.Exists(newName))
    {
        newName = String.Format("{0}{1}.{2}", fileName, i, extension);
        i++;
    }
    return newName;
}