C# 4.0 optional parameters are great!

I downloaded Visual Studio 2010 Beta 2 few weeks ago and I’m trying it out along with learning TDD and MVP presentation pattern. When writing unit tests, we often need to pass a mock dependency to an object through it’s constructor, so that we can test the interaction between the mock object and our tested object. It requires adding a new argument to the constructor, but we might not always need to pass it.

Before C# 4.0, we’d use constructor overloading, like this:

public SampleClass(int argument): this(argument, null)
{
}

public SampleClass(int argument, DependencyClass dependency)
{
    this.memberValue = argument;
    this.memberDependency = dependency;

    // if the dependency was not supplied, use IoC container to get it
    if(dependency == null)
       this.memberDependency = Resolve();
}

That required to have two constructors, even though the first one is empty. That changed in C# 4.0:

public SampleClass(int argument, DependencyClass dependency = null)
{
    this.memberValue = argument;
    this.memberDependency = dependency;

    // if the dependency was not supplied, use IoC container to get it
    if(dependency == null)
       this.memberDependency = Resolve();
}

Notice that we only have one constructor implementation and the second argument is assigned a default value, in case it was not supplied (those who know SQL Stored Procedures should grasp it immediately). Usage of this constructor remains the same:

SampleClass instance = new SampleClass(1);
// or
DependencyClass dependency = new DependencyClass();
SampleClass instance2 = new SampleClass(1, dependency);

Both ways work. It’s important to notice that the default values you assign to arguments must be compile time constants though.

Time to get rid of those empty overloads in your code! 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s