Since the very beginning of .NET evolution many developers felt the need in optional parameters. VB.NET had them, while C# developers had to implement function overloads to represent various versions of the same function, therefore repeating the same code multiple times just to make it usable in various situations.
With C# 4.0 there are now optional parameters that can be set for functions and constructors. Optional parameters get a default value that is used if no explicit change for that value is specified. So, the optional parameter cannot be omitted directly by the developer – it still needs a value, but it can be omitted later in the function call.
Let’s take a sample function that prints in the Output window:
void PrintToOutput(string line1, string line2 = "This is optional")
Now, I am going to call it with all the parameters passed to the function:
The final output will look like this:
If you noticed, when you were typing the function call, once you opened the parenthesis, the parameters that need to be passed are listed. The optional parameter is shown in square brackets:
The default value is also shown, so that the developer knows what the function is going to use if the parameter is not specified. Now, I am going to call the same function, without the second parameter. Here it is:
The output will look differently – the function took the default value for the parameter, as none was specified in the call:
Prior to C# 4.0, this had to be done by overloading:
void PrintToOutput(string line1)
void PrintToOutput(string line1, string line2)
Overloading is still present in C# 4.0, however, an analogue method to it is already available that can eventually save some space in the code window and make the code more readable. To demonstrate this on a very specific example, you will notice the change in code volumes when working with Office Interop. Since the majority of the calls can request numerous parameters, typing all of them can cause the code to become quite bulky, especially since many of the parameters are something like Type.Missing. Now, you can just pass the needed parameters and reduce the call to 2 or none parameters specified explicitly.
But let’s take a look under the hood of a function with optional parameters. To do this, I am going to launch the MSIL disassembler and open the compiled executable. When I look at the PrintToOutput function, I can see this IL interpretation:
.method private hidebysig instance void PrintToOutput(string line1,
[opt] string line2) cil managed
.param  = "This is optional"
// Code size 16 (0x10)
IL_0002: call void [System]System.Diagnostics.Debug::Print(string)
IL_0009: call void [System]System.Diagnostics.Debug::Print(string)
} // end of method Form1::PrintToOutput
As you see, the [opt] attribute directly specifies that the second parameter is optional, so it is not automatically interpreting the function from an overloaded point of view.