Optional Parameters, Default Values and Named Arguments in C# Programming Version 4.0

Introduction

Named Arguments let you specify the argument explicitly by strictly associating the argument with the parameter rather than its position in the method signature. This concept allows you to forget positional appearance and target parameters with their name.

Optional Parameters, as the name suggests, let you omit values for the parameters defined in the signatures. These optional parameters also lets you rely on default values defined in the method signatures.

Default Values lets you specify default values to arguments in a method signature, so that they may be skipped in the method calls that do not wish to modify the default values. This lets us avoid the process of creating several overloaded methods to achieve a solution to this problem.

All of these concepts can be used in methods, constructors, or delegates and most importantly in calls to COM Interfaces/ Interops. It is important to note that when the named arguments and optional parameter concepts are used, the arguments are evaluated in the order in which they appear and not the parameter list.

There are some basic rules that have to be followed when we create a method signature with these concepts. They are listed as follows:

  • Optional parameters do not replace the ref or the out parameters. Hence, optional parameters cannot be ref/out parameters.
  • The Default value specified for a parameter must be a constant value at compile time. It can also be the default value of the underlying type of the parameter.
  • Optional parameters should precede the Required Parameters. However, Params which do not have a default value can override this rule.
  • Named arguments should appear at the end, if they are used in conjunction with default positional arguments.

These new concepts also help you to write better LINQ Queries especially in simplifying the SELECT projection by allowing variations of a type’s constructor with a lesser set of parameters. (This information is from the sample chapter from the MSDN download website.)

Optional Arguments

This new concept in the 4.0 Framework allows the definitions of a method, indexer or a delegate to specify that its parameters are optional. The Optional Parameters have a constant – default value by definition. Such arguments can be omitted.

As per the rules stated above, these Optional Parameters should be defined towards the end of the parameter list.

The following sample defines one required and one optional parameter.

  public double GetTemperatureInCity(string city, double ifCityNotfound = 25.0)

The following example from Ivan Bondy’s Blog throws more light at this concept.

     namespace OptionalNamespace
     {
           class OptionalExample
           {
                 static void Main(string[] args)
                  {
                      // Instance anExample does not send an argument for the constructor's
                      // optional parameter.
                     ExampleClass anExample = new ExampleClass();
                     anExample.ExampleMethod(1, "One", 1);
                     anExample.ExampleMethod(2, "Two");
                     anExample.ExampleMethod(3);
          
                     // Instance anotherExample sends an argument for the constructor's
                     // optional parameter.
                     ExampleClass anotherExample = new ExampleClass("Provided name");
                     anotherExample.ExampleMethod(1, "One", 1);
                     anotherExample.ExampleMethod(2, "Two");
                     anotherExample.ExampleMethod(3);
          
                     // The following statements produce compiler errors.
          
                     // An argument must be supplied for the first parameter, and it
                     // must be an integer.
                     //anExample.ExampleMethod("One", 1);
                     //anExample.ExampleMethod();
          
                     // You cannot leave a gap in the provided arguments.
                     //anExample.ExampleMethod(3, ,4);
                     //anExample.ExampleMethod(3, 4);
          
                     // You can use a named parameter to make the previous
                     // statement work.
                     anExample.ExampleMethod(3, optionalint: 4);
                 }
             }
     class ExampleClass
        {
            private string _name;
       
            // Because the parameter for the constructor, name, has a default
            // value assigned to it, it is optional.
            public ExampleClass(string name = "Default name")
            {
                _name = name;
            }
       
            // The first parameter, required, has no default value assigned
            // to it. Therefore, it is not optional. Both optionalstr and
            // optionalint have default values assigned to them. They are optional.
            public void ExampleMethod(int required, string optionalstr = "default string",
                int optionalint = 10)
            {
                Console.WriteLine("{0}: {1}, {2}, and {3}.", _name, required, optionalstr,
                    optionalint);
            }
        }
 

C# Programming: Default Value

The default values are to be specified with the argument in the method signature. Check the following sample that uses two parameters. The second parameter is the parameter that uses a default value of 25.

  public List<TemperatureProperties>  GetTemperatureIntensity(string city,  double temperature=25.0)
  {
    …..
  }

This method can be called in the following ways:

A)

  List  properties = GetCurrentTemperature("Nevada", 50.0)

B)

  List  properties = GetCurrentTemperature("Nevada",)

Microsoft Visual Studio does a good job of highlighting the default parameter in the intellisense.

More by Author

Must Read