Generating Relational Members
Alt+Insert | Relational Comparer
JetBrains Rider helps you helps you automatically overload relational operators and implementations of related interfaces using selected fields and properties. By default, JetBrains Rider will create an implementation of
IComparable<T>, and optionally, operators
≤ as well as an implementation of
IComparable are generated too.
In the example below, this command is used to generate relational members that takes into account
int _birthYear and
string _name fields when to compare objects of the
|Before generation||After generation|
| || |
To generate relational members
- In the editor, set the caret on the type name or within a type at the line where you want to insert relational members. If the caret is on the type name, the generated code will be added in the beginning of the type declaration.
- Press Alt+Insert or choose from the main menu. Alternatively, you can press Ctrl+Shift+A, start typing the command name in the pop-up, and then choose it there.
- In the Generate pop-up menu, select Relational Comparer.
- In the Generate dialog that appears, you will see a list of properties and fields. Select the members that you want to use for type comparison.
If there are no fields/properties in your type or you do not select any of them, JetBrains Rider, depending on your settings, throws new
NotImplementedException(), returns default value, or puts code that will not compile in the body of the generated methods.
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 JetBrains Rider 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. JetBrains Rider 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.
- CompareTo already exists — appears if an implementation of
CompareTo()already exists and lets you choose whether to:
- Replace the method if it already exists.
- Put the newly generated method side by side with the existing one.
- Skip generating a new method altogether.
- Implement IComparable interface — tick this checkbox to generate an implementation of
IComparableinterface in addition to
IComparable<T>, i.e. generate the
CompareTo(object)method in addition to
- Click OK to complete the wizard.