Tuesday, 4 June 2013

Optional arguments (default arguments) in C#

C# has a syntax for defining optional/default arguments for a method, thus minimising the number of necessary method overloads. Usually, to provide a method that takes in a variety of argument combinations, you would have to have many overloads with different method signatures (arguments).


However, this means you will often end up with methods that do nothing except calling their overload with default arguments specified. So, rather than filling up your class with redundant methods, you can use optional argument syntax in C#.

There is no restriction on how many optional arguments you can use, but all of them have to come after other non-optional parameters. When they are omitted on a method call, default value specified in the method signature will be used automatically. It is also possible to explicitly choose the order in which the arguments comes in the method call, making it much more flexible and sometimes more clear. This is called 'Named Arguments', and the syntax is;  method(arg: value).

 Imagine you have 7 optional arguments, and you only want to provide 1st and 4th arguments. It would be much simpler both to use and to understand if you use Named arguments.

No comments:

Post a Comment