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 });

2 Responses to C# 4.0: Alternative To Optional Arguments

  • Geoff Smith says:

    That’s interesting, I’ve recently been wrestling with a problem where this was one of the possible solutions. I ended up with a constructor that takes 16 arguments.

    It’s absolutely horrid, but I was put off doing something like this because I felt I was repeating the structure too much. I was getting a fairly complex object from an (ugly) API and converting into something that would be used in my system rather than expose my entire system to that API.

    A bit over-the-top perhaps I also didn’t want to just pass the API object to my class, mainly because I would then need a separate constructor for my unit tests. So I have a factory style method that pulls the bits I need from the API method and passes them to my beast-like constructor.

    Anyways, I think I’m going to have another think about using the arguments class pattern.

  • paulo says:

    I give up well under 16 arguments. If you have 4 arguments and are all optional, you’ll came up with an insane number of overloads.

    The arguments class is more extensible and maintainable and, with the new object initializer syntax, you’ll write almost the same.