C# 4.0 Optional Parameters and Named Parameters

Posted by rusty

I have been resisting the new Optional Parameter feature of C# 4.0 due to the way I thought it would implement rather then diving into it and finding out. I was afraid it was going to be similar to Visual Basic and none of us want to go there. Turns out optional parameter combined with named parameter are nice enhancements to C#. These features certainly don’t replace method overloading but add much needed flexibility to the language.

Here is the more traditional way of overloading methods.

   1:  
   2:          static void AddToEmailList(string FirstName, string LastName)
   3:          {
   4:              Console.WriteLine("Person: {0}, {1}", LastName, FirstName);
   5:          }
   6:  
   7:          static void AddToEmailList(String FirstName, String LastName, String City, String State)
   8:          {
   9:              Console.WriteLine("Person: {0}, {1} from {2} {3}", LastName, FirstName,City,State);
  10:          }
  11:  
  12:          static void Main(string[] args)
  13:          {
  14:  
  15:              AddToEmailList("John", "Doe");
  16:              AddToEmailList("John", "Doe", "Parrish", "FL");
  17:              
  18:              Console.ReadLine();
  19:          }

Now for the improved optional parameter method of doing the same thing. Also lets add a named parameter for the third call of AddToEmailList.

   1:   static void AddToEmailList(String FirstName, String LastName, String City = "Tampa", String State = "FL")
   2:          {
   3:              Console.WriteLine("Person: {0}, {1}, from {2} {3}", LastName, FirstName, City, State);
   4:          }
   5:  
   6:          static void Main(string[] args)
   7:          {
   8:  
   9:              AddToEmailList("John", "Doe");
  10:              AddToEmailList("John", "Doe", "Parrish");
  11:              AddToEmailList("John", "Doe", State: "GA");
  12:  
  13:              Console.ReadLine();
  14:          }

Notice the default values for both city and state. If nothing is supplied then those values will be used. Also, noticed that if you want to change the 4th parameters “STATE” without supplying the 3rd parameters you must used named parameters.

AddToEmailList("John", "Doe", State: "GA" );

By adding the State: prior to the value you are in effect namely the parameter you will to change. It should also be noted that all normal parameters, or none default parameters, must be supplied first in your method declaration.

image

DotNetKicks Image


Comments

4/26/2010 1:08:57 PM

trackback

C# 4.0 Optional Parameters and Named Parameters

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com