How to fake Optional Parameters in c# 2.0

comments

With the launch of .Net 4.0 there have been a lot of excitement about some of the new features, Optional parameters being one of these. What a lot of people don’t realised it that with a bit of leg work you can pull this off with c# 2.0 – so those of you unable to deploy to a machine running .Net 4.0 can still join the party.

cSharp Optional parameters enable you to omit arguments for some of your methods’ parameters, as well as assigning default values to the ones that aren’t added to the call. Sadly, unlike Visual Basic, c# has sadly been lagging behind with its support for this feature. VisualBasic.Net has had this for quite some time. While we can all have a cry about this situation, let’s get on with it.

I have seen a lot of examples where people simply attempt to overcome the missing support in c# 2.0 by creating lots of method overloads – although i am not saying that what i am about to show you is the absolute cleanest implementation replacement, i strongly believe it to be superior to managing a codebase with many many method overloads.

So what do we do?

Well although as mentioned this solution is far from a perfect implementation replacement of the usage you have in .Net 4.0, you’ll see that it all comes down to the use of object arrays and the params keyword on your methods' parameters. Add these syntactic sugar and your on the way:

public void MyOptionalParameterMethod(params object[] parameterObjects)
{
    foreach (object o in parameterObjects)
    {

    }
}

And this can be very easily called like this:

MyOptionalParameterMethod("string1", "string2");

Extra leg work

You’ll quickly notice that this, while allowing you to have some parameters as optional, this also requires you to put in a little extra effort, as you’ll have to work out what is what when it comes to these incoming parameters.

I find that usually this is not a problem, as the times i have had to use it, my parameters have usually had different types. This would allow me to check the type of the parameter and therefore handle what each parameter does.

A quick example below will show you that i can separate the parameters simply by getting its type using the magical powers of reflection – you’ll notice that my example below not only achieves separating the parameters, but also sets default properties when i initialise the private objects in the first two lines of the method.

public void MyOptionalParameterMethod(params object[] parameterObjects)
{
    string strMyStringParameter = "Default string";
    int intMyIntParameter = 10;

    foreach (object o in parameterObjects)
    {
        switch (o.GetType().ToString())
        {
            case "System.String":
                strMyStringParameter = (string)o;
                break;
            case "System.Int32":
                intMyIntParameter = (int) o;
                break;
        }
    }
}

And i would call it like this:

MyOptionalParameterMethod("string1", 10);

Thar be dragons!

There is one slight downfall to this approach in the fact that i use reflection. If the method was repeatedly called or was a business critical part of code i wouldn’t recommend using this, as reflection by its very nature will always be slower than the method overload approach talked about at the beginning of this post.

Having said this, don’t take this as a “scare” piece about reflection – My fellow Ninja Rick Strahl has a great post about the non-scariness of using reflection here and i agree that the usual difference in practice will be 2 tenths of a blink of the eye – this usually won’t matter unless you’re really worried about speed.