Thursday, September 26, 2013

Optional Parameters in C#

A parameter is optional if it specifies a default value in its declaration.

The default value of an optional parameter must be specified by a constant expression, or a parameterless constructor of a value type. Optional parameters cannot be marked with ref or out.

default value examples:

// use default() keyword to obtain the default value of any type.
public void Problem(Guid optional = default(Guid)) {
}

or

// a parameterless constructor of a value type.
public void Problem(Guid optional = new Guid()) {
}

Note: new Guid(), which is equivalent to default(Guid).

Note: the new Guid() value is only applicable when:

  • You're really calling the parameterless constructor
  • Foo is a value type

Mandatory parameters must occur before optional parameters in both the method declaration and the method call (the exception is with params arguments, which still always come last).

Reference:
C# 5.0 in a Nutshell: The Definitive Reference
http://stackoverflow.com/questions/5117970/how-can-i-default-a-parameter-to-guid-empty-in-c

No comments: