C# Constructors and .NET 4.0 Optional Parameters

When a class defines multiple constructors, it is common to package up data validation and member assignments into the constructor defining the greatest number of arguments (sometimes called the ‘master constructor’).  When you do so, you can simplify the maintenance of the type, in that all the core startup logic is isolated, and can be easily updated as business rules change. The remaining constructors of the class can simply “Pass the buck” to the master, supplying any missing values. Consider the following class definition:

 

Code Snippet
  1. class Motorcycle
  2. {
  3.     public int driverIntensity;
  4.     public string driverName;
  5.  
  6.     // Constructor chaining.
  7.     public Motorcycle()
  8.     {
  9.         Console.WriteLine("In default ctor");
  10.     }
  11.  
  12.     public Motorcycle(int intensity)
  13.         : this(intensity, "")
  14.     {
  15.         Console.WriteLine("In ctor taking an int");
  16.     }
  17.  
  18.     public Motorcycle(string name)
  19.         : this(0, name)
  20.     {
  21.         Console.WriteLine("In ctor taking a string");
  22.     }
  23.  
  24.     // This is the 'master' constructor that does all the real work.
  25.     public Motorcycle(int intensity, string name)
  26.     {
  27.         Console.WriteLine("In master ctor ");
  28.         if (intensity > 10)
  29.         {
  30.             intensity = 10;
  31.         }
  32.         driverIntensity = intensity;
  33.         driverName = name;
  34.     }
  35. }

 

The nice thing about using constructor chaining, is that this programming pattern will work with any version of the C# language and .NET platform. However, if you are targeting .NET 4.0 and higher, you can further simplify your programming tasks by making use of optional arguments as an alternative to traditional constructor chaining.

Optional arguments allow you to define supplied default values to incoming arguments. If the caller is happy with these defaults, they are not required to specify a unique value, however they may do so to provide the object with custom data. Consider the following version of Motorcycle which now provides a number of ways to construct objects using a single constructor definition:

 

Code Snippet
  1. class Motorcycle
  2. {
  3.     ...
  4.     // Single constructor using optional args.
  5.     public Motorcycle(int intensity = 0, string name = "")
  6.     {
  7.         if (intensity > 10)
  8.         {
  9.             intensity = 10;
  10.         }
  11.         driverIntensity = intensity;
  12.         driverName = name;
  13.     }
  14. }

With this one constructor, you are now able to create a new Motorcycle object using zero, one or two arguments. Recall that named argument syntax allows you to essentially 'skip' over acceptable default settings.

 

Code Snippet
  1. static void MakeSomeBikes()
  2. {
  3.     // driverName = "", driverIntensity = 0
  4.     Motorcycle m1 = new Motorcycle();
  5.     Console.WriteLine("Name= {0}, Intensity= {1}",
  6.     m1.driverName, m1.driverIntensity);
  7.  
  8.     // driverName = "Tiny", driverIntensity = 0
  9.     Motorcycle m2 = new Motorcycle(name:"Tiny");
  10.     Console.WriteLine("Name= {0}, Intensity= {1}",
  11.     m2.driverName, m2.driverIntensity);
  12.  
  13.     // driverName = "", driverIntensity = 7
  14.     Motorcycle m3 = new Motorcycle(7);
  15.     Console.WriteLine("Name= {0}, Intensity= {1}",
  16.     m3.driverName, m3.driverIntensity);
  17. }

While the use of optional / named arguments is a very slick way to streamline how you define the set of constructors used by a given class, do always remember that this syntax will lock you into compiling your software under C# 2010 and running your code under .NET 4.0. If you need to build classes which can run under any version of the .NET platform, it is best to stick to classical 'constructor chaining' techniques.


Posted by: Andrew Troelsen
Posted on: 1/12/2010 at 1:48 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Pingbacks and trackbacks (1)+

Comments are closed
Contact Us 651-994-8558 1-800-866-9884
Home | Training | Curriculum | Course Finder | Schedule | Enroll | Twin Cities Java User Group | Consulting | Foundation | Jobs | About Us | Our Story | Press Room | Instructors | President | Map & Directions | Sitemap

Java Training | JSF / Struts / Spring / Hibernate Training | Java Power Tools Training | .NET 4.0 & Visual Studio 2010 Training | .NET 3.5 and Visual Studio 2008 Training | .NET 2.0 and Visual Studio 2003 Training | Prism / MVVM / MEF Training | Microsoft Web Development Training | Cloud Computing Training | Ajax / Web Services / XML Training | Groovy and Grails Training | SQL Server 2008 Training | SQL Server 2005 Training | Mobile Development Training | SharePoint 2010 Training | SharePoint 2007 Training | Agile, Process, Analysis & Design Training | Arch/Design Patterns Training | Microsoft Official Curriculum Training | Web Development Training | Ruby Training | Rational Application Developer (RAD) Training | WebSphere Application Server Training | WebSphere Portal Training | WebLogic Training | Boot Camp Training | Project Management Training | C++ Training | Metro / WinRT / Windows 8 Development Training | Retired

Intertech delivers training on-site and virtually serving cities including Phoenix, AZ | San Francisco, CA | Los Angeles, CA | San Diego, CA | San Jose, CA | Washington, DC | Chicago, IL | Orlando, FL | Boston, MA | Duluth, MN | Minneapolis St. Paul, MN | Rochester, MN | Raleigh-Durham, NC | New York, NY | Philadelphia, PA | Austin, TX | Dallas, TX | Houston, TX | Seattle, WA.