Convert Method to Indexer refactoring
This refactoring helps you convert methods that access collections into indexers and update method usages accordingly. You can apply it to:
A method with return value and one or more parameters to convert it into the
get
accessor of an indexer with the same set of parameters.A method with
void
return type and two or more parameters (the last of which is expected to be a value and the others represent the index) to convert it into theset
accessor of an indexer.
tip
The reverse functionality is available with the Convert Indexer to Method refactoring refactoring.
Consider the following example. If no indexer exists, the refactoring will create it:
Before refactoring
class TestBookLibrary{ Book[] _books; Book GetBookAt(int index) { return _books[index]; } void Insert(int index, Book book) { _books[index] = book; } void Copy(int copy, int to) { Insert(to, GetBookAt(copy)); }}
Applied to 'GetBookAt'
class TestBookLibrary{ Book[] _books; Book this[int index] { get { return _books[index]; } } void Insert(int index, Book book) { _books[index] = book; } void Copy(int copy, int to) { Insert(to, this[copy]); }}
If an indexer with only one of the accessors exists, the refactoring will try to add the second accessor if the converted method fits:
Indexer with one accessor exists
class TestBookLibrary{ Book[] _books; Book this[int index] { get { return _books[index]; } } void Insert(int index, Book book) { _books[index] = book; } void Copy(int copy, int to) { Insert(to, this[copy]); }}
Applied to 'Insert'
class TestBookLibrary{ Book[] _books; Book this[int index] { get { return _books[index]; } set { _books[index] = value; } } void Copy(int copy, int to) { this[to] = this[copy]; }}
Place the caret at the declaration or a usage of a method in the editor, or select it in the Structure window window.
Do one of the following:
Press CtrlShift0R and then choose Convert Method to Indexer.
Choose Refactor | Convert Method to Indexer from the main menu.
If no conflicts are found, JetBrains Rider performs the refactoring immediately. Otherwise, it prompts you to resolve conflicts.
tip
Right after the refactoring has been completed, all changes that it makes anywhere, including other files, are registered as a single operation. So you can use the Undo action Ctrl0Z to roll back all these changes with a single keystroke.