Tuesday 10 July 2012

Optional and Named Parameters in C#

As I mentioned a my previous post, I've recently started work in a new project that uses Microsoft Dynamics CRM 2011 and one of the first things I was asked to do was to write a method with a number of mandatory  [3] and optional [6] arguments/parameters of different types.

I thought to myself, this is great, now I have to write a lot of pointless logic to check whether the arguments/parameters have been passed in or use params and an object array plus a lot of logic to check what is being passed in. I dismissed passing in a complex object as there were too many permutations, which would require many many constructors and this is where I remembered reading about the new features of .NET Framework 4.0, which supports Optional and Named arguments/parameters.

The former are as their name would suggest optional and the latter are simply a way of calling optional parameters, so here is my method's signature, I won't explain the details as they are not relevant:

public AppointmentProposal[] GetAppointmentProposals(Guid SiteId, 

Guid ServiceId, int Duration, Guid? UserId = null, DateTime? Earliest = null,

DateTime? Latest = null, int MaxRows = 15, int SearchWindowRange = 7, 

int UserTimeZoneCode = 1)

The optional arguments/parameters have been give a default value, which means that if they are not passed in the default value will be used. This means that to a certain extent you still have to do some checking but it's a lot less checking that if you have to check whether the parameter is there.

In order to call the above method with mandatory parameters only, this is what you need, where SiteId and ServiceId are of type Guid.

GetAppointmentProposals(SiteId,ServiceId,60)

When invoked like this, GetAppointmentProposals will have the UserId, Earliest and Latest parameters set to null and the other three parameters will have their default values, namely: MaxRows will equal 15, SearchWindowRange will equal 7 and UserTimeZoneCode will equal 1.

If you want to change the MaxRows parameter, then you would invoke it like this:

GetAppointmentProposals(SiteId,ServiceId,60, MaxRows: 10)

When invoked like this, GetAppointmentProposals will have the UserId, Earliest and Latest parameters set to null and the other two parameters not specifically mentioned will have their default values, namely: SearchWindowRange will equal 7 and UserTimeZoneCode will equal 1 where MaxRows will equal 10.

Hopefully, that should clarify why they are called named parameters.

No comments:

Post a Comment