Skip to main content

Can combine initialization with declaration

In This Article

CodeRush Classic shows the Can combine initialization with declaration code issue if the initialization of a variable is split from its declaration provided that both are located in the same scope.

#Fix

Move initialization to declaration.

#Purpose

Shows the variable assignment statements, which can be combined with appropriate declaration statements. Combining variable initialization with a declaration decreases the number of lines in your code and improves the code readability.

#Example

public string FindStrings(string part, string[] stringArray)
{
    string result;result = "The following strings found:";
    foreach (string str in stringArray)
        if (str.Contains(part))
            result += string.Format("\r\n\t{0}", str);
    return result;
}

Fix:

public string FindStrings(string part, string[] stringArray)
{
    string result = "The following strings found:";
    foreach (string str in stringArray)
        if (str.Contains(part))
            result += string.Format("\r\n\t{0}", str);
    return result;
}