Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C# 4.0: Alternative To Optional Arguments

0.00/5 (No votes)
17 Apr 2010 1  
C# 4.0: Alternative To Optional Arguments
free hit counters

Like I mentioned in my last post, exposing public methods with optional arguments is a bad practice (that’s why C# has resisted having it, until now).

You might argue that your method or constructor has too many variants and having ten or more overloads is a maintenance nightmare, and you're right. But the solution has been there for ages: have an arguments class.

The arguments class pattern in the .NET Framework is used by several classes, like XmlReader and XmlWriter that use such patterns in their Create methods, since version 2.0:

C#
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Auto;
XmlReader.Create("file.xml", settings);

With this pattern, you don't have to maintain a long list of overloads and any default values for properties of XmlReaderSettings (or XmlWriterSettings for XmlWriter.Create) can be changed or new properties added in future implementations that won't break existing compiled code.

You might now argue that it’s too much code to write, but, with object initializers added in C# 3.0, the same code can be written like this:

C#
XmlReader.Create("file.xml", new XmlReaderSettings 
	{ ValidationType = ValidationType.Auto });

Looks almost like named and optional arguments, doesn't it? And, who knows, in a future version of C#, it might even look like this:

C#
XmlReader.Create("file.xml", new { ValidationType = ValidationType.Auto });

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here