Paulo Morgado

.NET Development & Architecture

Recent Articles

view all

Events

Projects

Recent Readers

Visitor Locations

Visitor Locations

Disclaimer

The opinions and viewpoints expressed in this site are mine and do not necessarily reflect those of Microsoft, my employer or any community that I belong to. Any code or opinions are offered as is. Products or services mentioned are purchased by me, made available to me by my employer or the manufacturer/vendor which doesn't influence my opinion in any way.

C# 4.0: Alternative To Optional Arguments

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

You might argument that your method or constructor has to 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 is used in the .NET Framework is used by several classes, like XmlReader and XmlWriter that use such pattern in their Create methods, since version 2.0:

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:

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:

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

Comments

No Comments