Convert Indexer to Method refactoring
This refactoring helps you convert one or both accessors of an indexer into methods and update usages of the indexer in the current solution accordingly.
In the example below JetBrains Rider converts both getter and setter accessors of the indexer and updates the usage:
Before refactoring | After refactoring |
---|---|
class BookLibrary
{
private Book[] books = new Book[1000];
public Book this[int index]
{
get
{
if (index >= books.Length)
throw new IndexOutOfRangeException("incorrect index");
return books[index];
}
set
{
if (index >= books.Length)
throw new IndexOutOfRangeException("incorrect index");
books[index] = value;
}
}
public void TestInsertBookAt(Book book, int index)
{
this[index] = book;
}
} | class BookLibrary
{
private Book[] books = new Book[1000];
public void SetItem(int index, Book value)
{
if (index >= books.Length)
throw new IndexOutOfRangeException("incorrect index");
books[index] = value;
}
public Book GetItem(int index)
{
if (index >= books.Length)
throw new IndexOutOfRangeException("incorrect index");
return books[index];
}
public void TestInsertBookAt(Book book, int index)
{
SetItem(index, book);
}
} |
To convert an indexer to a method
- Place the caret at
this
keyword of an indexer in the editor or select an indexer in the Structure window. - Do one of the following:
- Press Ctrl+Shift+R and then choose Convert Indexer to Method(s)
- Choose in the main menu.
- Use controls in the dialog to choose which accessors should be converted and to specify names for the created methods.
- To apply the refactoring, click Next.
- If no conflicts are found, JetBrains Rider performs the refactoring immediately. Otherwise, it prompts you to resolve conflicts.
Last modified: 20 August 2018