Skip to content

Named arguments C# 4.0readability

Specify method parameters by name instead of position.

Sometimes passing values to methods can be quite unreadable. Booleans, integers and other constants aren't always clear without digging into the signature.

Named arguments let you optionally put the parameter name next to the value.

Additionally when a method has Optional arguments C# 4.0 they are used to specify which arguments are being passed without having to specify default values or nulls.

Code ​

csharp
GetCustomer(id: 1, eager: true, depth: 3);

// (Show use of optional arguments too)
Customer GetCustomer(int id, bool eager, Context context = null, int depth = 0)
{
    // ...
}
csharp
GetCustomer(1, true, null, 3);

Customer GetCustomer(int id, bool eager, Context context, int depth)
{
    // ...
}

Notes ​

  • Parameter names become part of your public API: renaming a parameter breaks callers that use its name
  • In C# 4.0 named arguments must come after all positional arguments; Non-trailing named arguments C# 7.2 relaxed this

More information ​

Powered by Intracia