Optional arguments and named parameters in C#
C# 4.0 supports optional method arguments. Related to this is support for named parameters in function calls. For us it makes easier to use methods which have long argument list. It also introduces some new dangers which may lead us to messy and hard to understand code. In this code I will show how to use optional arguments and give some hints how to avoid messy code.
I wrote simple application to illustrate default values and their usage.
static void Main(string args)
Console.WriteLine(GetArguments("one", "four", "five"));
Console.WriteLine(GetArguments("one", third: "five"));
Console.WriteLine("Press any key to exit...");
private static string GetArguments(string first,
string second = "two", string third = "three")
return first + " " + second + " " + third;
Example (not exact) output of this program is shown on image on right.
First three calls to GetArguments() are not something crucial and they follow current C# syntax.
Fourth call introduces named parameter. Notice how we are giving value to first and third argument. Syntax is very simple:parameter:value.
Optional arguments are widely used in VBA for long time. Although they make life a little bit easier for programmers (you don’t have to repeat default values in your method calls) there will be always danger that optional arguments are overused.
Too long argument lists refers to the need of parameter object (refactoring method calledIntroduce Parameter Object). Parameter object may also carry default values because you can assign initial values to object attributes and properties.
Of course, it is up to you and depends on context if you want to use method with many arguments or parameter object. If you know pitfalls then it is easier for you to make decisions.
2 thoughts on “Optional arguments and named parameters in C#”
Given the potential pitfalls, method overloading and parameter object should be the first choices.
A good post about optional parameters internals – http://devlicio.us/blogs/krzysztof_kozmic/archive/2009/09/03/thoughts-on-c-4-0-optional-parameters.aspx