After my posts on the framework features over the past couple of weeks, I will now start focussing on the language aspects of C# 4.0. In C# 4.0, named and optional parameters have been introduced. This is one feature that I have been waiting for so I am only glad that the .NET team has decided to introduce this feature in C# 4.0.
VB 6.0 programmers are aware of the usage of the optional parameters. It used to be declared as
Sub DoSomething(Optional ByVal Switch As Boolean = False)
What the above declaration meant was that you could call the DoSomething method without explicitly passing the Switch parameter. The default value of false will be assigned to the variable if it was not passed.
This was not possible in .NET. The workaround was to declare overloaded methods. You do not need to do that anymore. In C# 4.0, you can declare a method with an optional parameter simply by assigning a default value for the parameter in question like the example below.
private string Extract(String inputString, int endIndex=0, int startIndex =0)
Named parameters as the name suggests, enable the developers to skip a parameter while calling the method if they wish to. This is done by passing the parameter by quoting its name and value separated by a colon as shown in the syntax below
Extract(inputString, startIndex: 4);
The syntax above calls the method extract with three parameters the signature of which is described previously. You will notice that the second parameter endIndex has been skipped and the value is being passed for startIndex. Below is the complete code snippet
In the above example, the extract method just creates a substring for a specified start and end index. I have made three calls to the method. Note that with Named Parameters, the order in which you pass the parameters is not important as long as you don’t forget to name them correctly. You can see this in Line 17 of the above code.
That is it for this post on named and optional parameters. They are quite a useful feature that will reduce the number of overloaded methods that we will have to write. I am sure you will find more ways of putting them to use.