Use string.Compare

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 (<:caret:>msg.Substring(1, 4) == "rror")
            return true;
        return false;
    }
    
  2. Use 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", false) == 0)
        return true;
    return false;
}

You can use the ignoreCase parameter to make the code above more clear and exact.

bool CheckError(string msg) {
    if (string.Compare(msg.Substring(0, 5), "error", true) == 0)
        return true;
    return false;
}
See Also