What’s new in C# 4.0: Part 1: Optional Parameters & Named Parameters
Friday, 11 June 2010 at 1:33 pm AEST | Trackback
Optional Parameters
Prior to C# 4.0 the best method for optional parameters was method overloading. However, now C# 4.0 ships with the ability to have optional parameters, which are very simple to use.
The biggest impact I think this will have is in COM interop, where you used to have to specify a value for each parameter, optional or not.
Optional parameters are defined at the end of the parameter list, after required ones. Also, you may not specify any gaps in the argument list. If you provide an argument for an optional parameter, you must specify values for the previous parameters. However, if you know the name of the parameters you can get around this. For example here is a method to send an email:
private void SendEmail(string AddressTo, string AddressFrom, string Subject = "Important", string Signature = "Sent From Email Client") { // ... } |
So, the following call is not valid and will result in a compile error:

However, the following named call will work fine:

Each optional parameter you specify must have a default value, so if no argument is specified then the default value will be used. These default values must be constants. So, back to our previous method, “Subject” and “Signature” are both optional parameters:
private void SendEmail(string AddressTo, string AddressFrom, string Subject = "Important", string Signature = "Sent From Email Client") { // ... } |
Named Parameters
As you saw in optional parameters, another new feature is named parameters. Named parameters are helpful so you do not have to lookup the order of arguments for a method.
There is only one convention for named parameters, being that a named argument can not proceed a positional argument, however the opposite is acceptable.
Here is an example method:
private string ReverseName(string FirstName, string LastName) { // ... } |
We can used named parameters to change the order of the arguments:
string ReversedName = ReverseName(LastName: "Payne", FirstName: "Luke"); |
Using named parameters can increase readibility of your code.
Look out for Part 2, coming soon!
