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.



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

C# Programming: Named Arguments

The Named Arguments show us their use when we program with COM Interop methods.

You can avoid all optional parameters (remember Sytem.Reflection.Type.Missing?) and only provide the required parameter through named arguments concept. There are various good examples already on the web of this.

In particular, the example by Joydip Kanjilal in the article titled "COM Interop Gets Much Better in C# 4.0", shows you exactly what you need. Below is the extract from the article that talks about the usage of Named Arguments.

For example, here's the pre-4.0 C# programming code you need to write to open a Word document:



	  using Word = Microsoft.Office.Interop.Word;
	  namespace COMInterop
	        {
	     class Program
	           {
	        static void Main(string[] args)
	              {
	           	Word.Application wordApplication = 
	              	new Word.Application() { Visible = true };
	           	object missingValue = System.Reflection.Missing.Value;
	          	 object readOnlyValue = true;
	          	 object fileName = @"C:\\DevX.docx";
	          	 wordApplication.Documents.Open(ref fileName, ref 
	             	 missingValue, ref readOnlyValue,
	             	 ref missingValue, ref missingValue, 
	             	 ref missingValue, ref missingValue, 
	             	 ref missingValue, ref missingValue,
	              	ref missingValue, ref missingValue, 
	             	ref missingValue, ref missingValue, 
	             	ref missingValue,ref missingValue);
	        		}
	     	    }
	  	}	
	

In the Open call in the last line, you can see that you need to pass a number of optional parameters just to satisfy the method call. With the introduction of optional and named parameters in C# 4.0, you can do the same with much less code.

Here's the code you can use to open a word document in C# 4.0:

  using Word = Microsoft.Office.Interop.Word;
  namespace COMInterop
  	{
    class Program
     	{
        static void Main(string[] args)
        	    {
           Word.Application wordApplication = new 
              Word.Application() {Visible = true};   
           wordApplication.Documents.Open(@"C:\\DevX.docx", 
              ReadOnly: true);
        	}
     }
  }

A named argument undoubtedly makes your code more clear. For example, look at the following code sample.

  public CityInformation  GetCityInformation(string city, string country)
   {
  ….
  }

The above method would be called as follows:

  CityInformation ci = GetCityInformation("Vancouver", "Canada");

However, with the usage of named arguments you could do this:

  CityInformation ci = GetCityInformation(city:"Vancouver", country:"Canada");

Also note that, if you add a parameter as optional to a method that is public by definition and is called from another assembly, then you would require recompiling both the assemblies. The compiled version would add the code equivalent to the method being called with the default value.

Look at the references section for more information.

Hope this article was informative. Thanks for reading.

References

Named and Optional Arguments (C# Programming Guide)
Ivan Bondy's Blog
COM Interop Gets Much Better in C# 4.0

Related Articles





About the Author

Srinath M S

I would love to leave a footprint in this flat world

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds