Monday, 1 June 2015

Default and Named Parameters

Default and Named Parameters were new features in C# 4.0

Default Parameters

Methods can take parameters that are optionally nullable like thus:-

public void SomeMethod(DateTime? time)

In C# 4.0 This can be called by this code
SomeMethod();

As the parameter is nullable it is now also optional.  Optional parameters can only be listed after all required parameters.  There are two syntaxes for doing this


  1. Optional Keyword
    Requires the addition of another using statement as well as the optional attribute

    using System.Runtime.InteropServices;

    public void SomeMethod([Optional] DateTIme? time)

    If the caller doesn't provide a value for an optional parameter then it will be assigned the type's default value (null for reference types, 0 for many numeric types).
  2. Specify a default value
    Doesn't require the using statement.  This also allows you to specify what the default value is

    public void SomeMethod(DateTime? time = null, int value = 3) 

    Note the compiler must be able to compute the value provided; It must be a compile time constant.   You couldn't use DateTime.Now() as a constant for example. 

Named Parameters

When calling a method and passing in parameters it can be unclear what the parameters are for, particularly if you pass null as one of the parameters.  You can name the parameters in the call (the name must match that given in the signature) with a colon and the value to pass to that parameter in the method call.

SomeMethod(time: DateTime.Now);
SomeMethod(value: 3);

In the second example above the time parameter is omitted and hence it gets the default value, null.
This is useful for the situation where parameters or values passed aren't very descriptive and make reading the code harder.

No comments:

Post a Comment