Optional and Named Parameters in C# Programming

Introduction

Welcome to this installment of the .NET Nuts & Bolts column! This time around we'll explore optional and named parameters in C#. This is an option that has long been around within the Visual Basic language, but is newly introduced in to the C# language in the .NET Framework 4.0.

Why Now?

The C# programming language has been around for 10+ years now depending upon whether you start the timer for its existence with the official release or include the beta period. For those with a Visual Basic history that pre-dates .NET you recognize optional and named parameters. If you're like myself and started out in the .NET framework with a transition to C# it's likely that you missed them for a while, but grew to appreciate overloading and having a number of methods with the same name with different signatures. Then eventually we forgot all about it after having gotten used to not having it in C#. Well, it's time to get reacquainted because optional and named parameters are now part of .

Let's first take a quick detour in to why they are finally in the C# language after all this time. The object oriented purists were happy to not have them. It's likely that they may not have made an appearance, but for a couple of key reasons. Reason number one is the new approach of the Microsoft language teams to have parity across the languages. Features will be released in VB.NET and C# at the same time as well as steps are being taken to close some of the gaps between the two so that there is a more consistent experience regardless of the language. Reason number two is the improved COM interoperability that was part of the objectives of the .NET Framework 4.0 release. Well rooted items such as the Microsoft Office COM support optional and named parameters rather than providing numerous method signatures with different parameters. The office API is firmly grounded and less likely to undertake a major overhaul. It is far simpler to add optional and named parameter support to C#.

// Original bloated C# code to Save a Word document
object fileName = "Test.docx";
object missing  = System.Reflection.Missing.Value;
  
doc.SaveAs(ref fileName,
	ref missing, ref missing, ref missing,
	ref missing, ref missing, ref missing,
	ref missing, ref missing, ref missing,
	ref missing, ref missing, ref missing,
	ref missing, ref missing, ref missing);
  
// Replacement slimmed down code now possible due to optional params
doc.SaveAs("Test.docx");

Optional Parameters in C# Programming

C# has classically used overloading in order to provide alternate method signatures. It commonly involves having a primary declaration will a complete parameter list, and additional overloads with a shortened parameter list. Commonly, the shorter declarations just call the primary with desired default values. This offers the behavior of optional parameters, but does require more code. The following code example demonstrates the concept.

// Primary declaration
public StreamReader OpenTextFile(
string path,
Encoding encoding = null,
bool detectEncoding = true,
int bufferSize = 1024)
{
	// Relevant method implementation here…
}

// Example calls leaving off parameters
OpenTextFile("foo1.txt", Encoding.UTF8, true, 2048);
OpenTextFile("foo2.txt", Encoding.UTF8, false);
OpenTextFile("foo3.txt", Encoding.UTF8);
OpenTextFile("foo4.txt");

Optional and Named Parameters in C# Programming

Named Parameters

As you look at the last example in the prior section, it is important to notice how each of the sample calls uses and omits the parameters in order. For any optional parameter that is omitted each of the subsequent parameters is also omitted by design. So what if you have a number of optional parameters where you want to rely on the defaults for a couple of them and want to specify a value for a parameter at the end of the method signature? This is the behavior that named parameters allow. The syntax for named parameters is the name of the parameter followed by a colon and the assigned value. A few rules of which you should be aware with named parameters:

  • Named parameters can appear in any order
  • Parameters are evaluated in the order they are written
  • Non-optional parameters must also be named
  • Named parameters must be last in the list of parameters if there is a mixture of non-named and named parameters

The following sample code demonstrates alternate calls to the previous example and uses named parameters as part of the example.

  // Name parameters after the first
this.OpenTextFile2("foo.txt", encoding: null, detectEncoding: true, bufferSize: 1024);

// Name all in any order
this.OpenTextFile2(detectEncoding: true, bufferSize: 1024, encoding: null, path: "foo.txt"); 
this.OpenTextFile2(bufferSize: 1024, path: "foo.txt", encoding: null, detectEncoding: true);
this.OpenTextFile2(detectEncoding: true, encoding: null, path: "foo.txt", bufferSize: 1024);

// Provide the first, optional parameters, name other
this.OpenTextFile2("foo.txt", encoding: Encoding.UTF8, bufferSize: 1024);
this.OpenTextFile2("foo.txt", bufferSize: 1024);

Like many other constructs, while named parameters allows you to specify the parameters in any order I would recommend that you apply it more sparingly rather than going around changing the order of all of your parameters.

Conclusion

We have explored optional and named parameters within C#. We started with an introduction of why the feature was added to the language now. We followed the introduction with a detailed look at optional parameters followed by details on named parameters, which complements optional parameters.

Future Columns

The topic of the next column is yet to be determined. If you have something else in particular that you would like to see explained here you could reach me at mark.strawmyer@crowehorwath.com.

Other .NET Nuts and Bolts Columns



About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.

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

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds