Generating Equality Comparer
IEqualityComparer<T> is a generic.NET interface that allows implementing customized equality comparison for collections.
Creating a comparer class for your type is an alternative to creating Equals() and GetHashCode() methods for the type. The generated comparer class will implement the
IEqualityComparer<T> interface and provide custom
In the example below, this command is used to generate the comparer class based on
To generate an equality comparer class
- In the editor, set the caret on the type name or within a type at the line where you want to insert an equality comparer class. If the caret is on the type name, generated code will be added in the beginning of the type declaration.
- Press Alt+Insert or choose in the main menu.
- In the Generate pop-up menu, select Equality Comparer.
If there are no fields/properties in your type or you do not select any of them, ReSharper, depending on your settings, throws new
NotImplementedException(), returns default value, or puts code that will not compile in the body of the generated methods. You can configure the settings on the page of ReSharper options.
Optionally, use the following controls in the dialog:
- Fields can be null — appears if there are any nullable fields or properties in your type. By default, this check box is selected, meaning that ReSharper will generate null checks for selected fields. You can clear this check box if you do not need null checks.
- String comparison — appears if there are any string fields in your type. ReSharper will generate
string.Compare(string, string, StringComparison)for the selected strings, and the selector lets you choose which value should be generated for the StringComparison argument.
- Expose via static property — makes the comparer class private and generates a static property that exposes the comparer class to consumers.
- Comparer name prefix — allows you to specify a prefix that will be used in the name of the generated comparer class.
- Click Finish to complete the wizard.
You can also click Options to review or modify common code generation preferences on the page of ReSharper options.
This feature is supported in the following languages and technologies:
The instructions and examples given here address the use of the feature in C#. For details specific to other languages, see corresponding topics in the ReSharper by Language section.