Skip to main content

Use String.Compare

  • 2 minutes to read

Purpose

Replaces the equality expression between two strings with the String.Compare method call. The String.Compare method is more flexible than the equality operator. For example, you can specify whether to ignore the letter case while comparing strings. This method also has better performance.

Availability

Available when the caret is on an equality expression between two strings.

Usage

  1. Place the caret on the equality expression between two strings.

    Note

    The blinking cursor shows the caret’s position at which the Refactoring is available.

    bool CheckError(string msg) {
        if (msg.Substring(1, 4) == "rror")
            return true;
        return false;
    }
    
  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
  3. Select Use String.Compare from the menu.

After execution, the Refactoring converts the comparison with the equality operator to the comparison with the String.Compare method.

bool CheckError(string msg) {
    if (String.Compare(msg.Substring(1, 4), "rror", StringComparison.Ordinal) == 0)
        return true;
    return false;
}
See Also