Home > Refactorings > Refactorings – Use Named Arguments

Refactorings – Use Named Arguments

June 28th, 2011

Named Arguments is a feature of the C# and Visual Basic languages introduced in the .NET Framework version 4.0. Named arguments allow you to explicitly specify a name for an argument for a particular parameter by associating the argument with the parameter’s name, rather than with the parameter’s position in the parameter list. Using named arguments frees you from the need to remember or to look up the order of parameters in the parameter lists of called methods.

The Use Named Arguments refactoring shipped in Refactor! Pro converts position-based arguments inside a usual call to a method with a call with named arguments, for example:

DrawPoint(10, 8, 12);

Result:

DrawPoint(x: 10, y: 8, z: 12);

In the code preview hint you are able to see the resulting code:

DevExpress Use Named Arguments refactoring preview

Named arguments become very useful when a method definition also contains several optional parameters, and you want to specify which arguments you are passing. For example, we have the following method declaration:

void DrawPoint(int x = 0, int y = 0)
{
  // code goes here...
}

We could use named arguments to call the above method in any of the ways below:

DrawPoint ();
DrawPoint (x: 10);
DrawPoint (y: 10);
DrawPoint (x: 10, y: 10);
DrawPoint (y: 10, x: 10);

Because both parameters of a method definition are optional, the first three cases will call a method with the default value passed for all non-specified arguments.

—–
Products: Refactor! Pro
Versions: 11.1 and up
VS IDEs: any
Updated: Jun/28/2011
ID: R029

Similar Posts: