Optional Parameters and Named Parameters In C# 4.0

A long-requested feature for C# was to allow for method parameters to be optional. Two closely related features in C# 4.0 fulfill this role and enable us to either omit arguments that have a defined default value when calling a method(optional parameter), and to pass arguments by name rather than position when calling a method(named arguments).

The main benefit of these features is to improve COM-Interop programming and to reduce the number of method overloads created to support a wide range of parameter overloads. It is a common programming pattern to have a master method signature containing all parameters (with the actual implementation) chained to a number of overloaded methods that have a lesser parameter signature set calling the master method with hard-coded default values. This common coding pattern becomes unnecessary when optional parameters are used in the definition of the aforementioned master method signature, arguably improving code readability and debugging by reducing clutter.

Let’s define an optional parameter:

public void ExampleMethod(int required, string optstr = "default string", int optint = 10)

You can call this method in 3 different ways

// Either you can pass only the required parameter
anExample.ExampleMethod(3);  

// Or you can pass only the first two parameters
anExample.ExampleMethod(3, “Passed option string”);

// Or you can pass all the three parameters
anExample.ExampleMethod(3, “Passed option string”, 10);

Note: all the optional parameters should be at the end. You cannot create a method with first parameter as option and then required.

Some invalid methods due to the order of optional parameter:

public void InvalidMethod(string optstr = "default string", int required)

public void InvalidMethod (string optstr = "", int required, int age = 10)

Let’s say you want to pass 1st parameter and 3rd parameter, was that possible before C# 4.0, No. Suppose I am trying to call the method like this:

 anExample.ExampleMethod(3, , 10);

It will immediately give the compilation error. But with the named value parameter it is possible we can do this by using the parameter name as follows:

  anExample.ExampleMethod(3,  optint = 10);

You may think, what benefit we will have by using the named parameter, just think….. Any Idea? You can pass parameters in any order by using the named parameter, no need to remember the order. But the biggest benefit you can see in next example.

COM-Interop code has always suffered due to C#’s inability to handle optional parameters as a concept. Many Microsoft Office Component Object Model (COM) libraries, like those built to automate Excel or Word for instance, have method signatures that contain more than 20 optional parameters. Previously you had no choice but to pass dummy arguments until you reached the “one” you wanted and then fill in the remaining arguments until you had fulfilled all. Optional parameters and named arguments solve this madness, making coding against COM interfaces much easier and cleaner. The code shown bellow demonstrates the before and after syntax of a simple Excel COM-Interop call to open an Excel spreadsheet. It shows how much cleaner this type of code can be written when using C# 4.0 versus any of its predecessors.

// Old way – before optional and named parameters
var excel = new Microsoft.Office.Interop.Excel.Application();
try
{
      Microsoft.Office.Interop.Excel.Workbook workBook =
      excel.Workbooks.Open(fileName, Type.Missing,
      Type.Missing, Type.Missing, Type.Missing,
      Type.Missing, Type.Missing, Type.Missing,
      Type.Missing, Type.Missing, Type.Missing,
      Type.Missing, Type.Missing, Type.Missing,
       Type.Missing);
       // do work with Excel...
       workBook.Close(false, fileName);
}
finally
{
      excel.Quit();
}




// Now– Using optional and named parameters
var excel = new Microsoft.Office.Interop.Excel.Application();
try
{
      Microsoft.Office.Interop.Excel.Workbook workBook = excel.Workbooks.Open(fileName);
      // do work with Excel...
      workBook.Close(false, fileName);
}
finally
{
      excel.Quit();
}

Isn’t is a better way to use the new code? Hope you'll like it.

Alicia Gonzalez Started career with .Net, and not working on client side technologies like angular, React etc. since last 12 years. But C# is really amazing language and I like to learn everything about C# and want to share whatever I know.
  • c#
By Alicia Gonzalez On 27 Jun, 12  Viewed: 863

Other blogs you may like

Polymorphism in C# with example

Polymorphism is derived from two Latin words, 1. Poly means many 2. Marphose means forms. By using inheritance, a class can be used as many types, say we have a Person which may be a Professor, may be a Student, may be Clerk. So in this article we will see some example of Polymorphism. When we... By Hamden   On 01 Jun 2013  Viewed: 4,150

How to create windows service in C# visual studio 2010

Creating windows service in C# is really easy but when we need to create first time we face many problems so in this post we will try to learn everything about window service. In this article we will create a windows service which will run after a particular interval, and time should be... By Ali Adravi   On 30 Apr 2013  Viewed: 8,231

Covariance and Contravariance in C# 4.0 with example

C# the language, right from the very beginning is always supported covariance and contravariance but in most simple scenario, now in C# 4.0 we have full support of covariance and contravariance in all circumstances, generic interface and generic delegates, other C# types already support from first... By Ali Adravi   On 29 Mar 2013  Viewed: 4,832

default value for different data type in C#

In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds... By Ali Adravi   On 27 Mar 2013  Viewed: 2,414

enum in C# and conversion

An enumeration type (also known an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable to make programming clear, understandable and manageable. There are ways of using, like how to use enum in switch and case statement,... By Hamden   On 27 Mar 2013  Viewed: 4,102