Skip to content

Optional arguments C# 4.0code reduction

Allow arguments to a method to be optional.

Sometimes you can perform an action on your object with a variety of parameters. Even if you choose multiple methods with the same name and different parameters there can still be places where some arguments to the method should be optional.

Previously you could document this and have people pass "null" in the argument but with C# 4 you can clearly state an argument is null and provide the default value together in the method signature.

Callers can then skip the arguments they don't want to pass and simply refer to all further arguments they do wish to pass by naming the arguments C# 4.0.

Code

C#
GetCustomer(1, true, depth:3);

Customer getCustomer(int id, bool eager, Context context = null, int depth = 0)
{
    // ...
}
C#
GetCustomer(1, true, null, 3);

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

More information