Named and Optional parameters are couple of good features that Visual Basic is enjoying all these days. Now .NET Framework 4.0 extended the support to these in C# 4.0. Even though Named parameters and Optional parameters are two different features, often they get referred together.
The salient feature of Named Parameters is you could pass the parameters in any order to the functional. You don't have to follow the order that the function definition was made. In order to use the method parameter, you just user parameter name:parameter value. Note the colon separator between parameter name and value. The following example shows how to define in C# 4.0 with named parameters.
private void PaintMe(int Red, int Green, int Blue, string TextBlock){//method functionality}
and you can call the parameters in any order like the following
PaintMe(Red:45, Green:45, Blue: 232, TextBlock:"This is almost Blue");
PaintMe(TextBlock:"This is almost Blue", Green:45, Blue:232, Red:45);
and so on....
Optional parameters can be defined same as regular parameters but they will have a default value. The Optional Parameters should follow the required parameters when defining and calling them. Now the method with Optional parameters can be defined as follows:
private void DoMagic(int MagicInt, float MagicFloat, string MagicString="I am Magic"){//method functionality}
and now it can be used like this:
DoMagic(1, 1.0, "I am Not The Only Magic");
DoMagic(2,2.2); //Now the default value of optional parameter MagicString will be used inherently
Optional parameters and named parameters make the code more readable and easily maintainable. If the method call is effectively implemented using optional parameters, then the method overloading can be simplified. We don't have to have separate definitions for each different type and number of parameters or combinations of various parameters.
An example for such situation is:
public void DoSomething(int intParam, float fltParam){..}
public void DoSomething(int intParam)
{
DoSomething(intParam, 1.0);
}
We can implement the same with the following one simple usage of optional parameters:
public void DoSomething(int intParam, float fltParam=1.0){...}
Of course, the real world usage would not be that simple, but they come very handy. Also Optional parameters will improve the COM Interop situations.
Remember the following rules must be followed:
- Non-optional parameters must be declared first
- If there are any non-optional parameters in your method declaration they must still used in making a method call.
- Parameters are evaluated in the order they are declared.
- If the method overloaded with two valid signatures and one has no optional parameters then that would be given precedence.