The Extract Method refactoring allows users to quickly create a new method based on a selected code fragment. ReSharper analyses the selected block of code and detects variables that can be converted into a method parameters or represent its return value.
The refactoring can be applied to any expression, not necessarily to the set of statements. In the table below, you can see some usage examples.
| Before | After |
|---|---|
public ArrayList Foo()
{
string[] strings = { "a", "ab", "abc" };
char[] chars = { 'a', 'b', 'c' };
ArrayList list = new ArrayList(strings);
for (int i = 0; i<list.Count; i++)
{
list[i] = ((string)list[i]).TrimEnd(chars);
}
return list;
}
|
public void Foo()
{
string[] strings = { "a", "ab", "abc" };
char[] chars = { 'a', 'b', 'c' };
ArrayList list = TrimStrings(chars, strings);
Console.WriteLine(list);
return list;
}
//extracted method
private ArrayList TrimList(char[] chars, string[] strings)
{
ArrayList list = new ArrayList(strings);
for (int i = 0; i<list.Count; i++)
{
list[i] = ((string)list[i]).TrimEnd(chars);
}
return list;
}
|
public void Foo(ICollection col)
{
//check for empty collection
if(col.GetEnumerator().MoveNext())
{
...
}
...
}
|
public void Foo(ICollection col)
{
//check for empty collection
if(IsEmpty(col))
{
...
}
....
}
//extracted method
public bool IsEmpty(ICollection col)
{
return col.GetEnumerator().MoveNext();
}
|
Warning If the selected code block has multiple exit points (for example, the block has a conditional return statement), the Extract Method refactoring can change the code semantic and produce uncompilable code.
Consider the following example:
public void Foo() { ... if(i>0) return; i++; Console.WriteLine(i); ... }If you try to extract a method from the selected code block, ReSharper will show a warning notifying that the refactoring is not safe.

Note Expressions detected as possible return values will have the out modifier in the parameters list.
If no conflicts are found, all the changes are applied immediately.