C# 4.0 – Optional Parameters

C

I know, I know, VB has had them for ages.

But I don’t care… Now C# has them too!

This will greatly reduce method overloads!
Check this bit of code (sorry it’s not a “real world” example)

public class TestClass
{
    public void DoSomething(string parameterOne, string parameterTwo, string parameterThree)
    {
        DoSomething(parameterOne, parameterTwo, parameterThree, null);
    }

    public void DoSomething(string parameterOne, string parameterTwo, string parameterThree, string parameterFour)
    {
        if (parameterFour != null)
        {
            //doing somthing with the parameters.
        }
    }
}

The DoSomething method has an overload on it that takes a fourth parameter (in this case parameterFour)

When we use the above code, our intellisense looks like this:

 

overload1

…and the second overload

 

overload2

As we can see, the method has 2 overloads. One taking parameterFour, one not.

New in C# 4.0, we can use something called optional parameters.

This allows us to change our method to:

public class TestClass
{
    public void DoSomething(string parameterOne, string parameterTwo, string parameterThree, string parameterFour = null)
    {
        if (parameterFour != null)
        {
            //doing something with the parameters.
        }
    }
}

As you can see, we’ve removed the overloaded method – I’m sure you can appreciate, if we had a method with many overloads, this results in much cleaner code 🙂

Now, our intellisense looks like this:

intellisense-with-optional-parameter-method

In my opinion, this looks a bit confusing.

Sure, I’ll get used to it, but in my opinion, the method is still sort of overloaded… just with optional parameters!