C# 4.0 Crash Course: Optional and Named Parameter

Parameters with default value. Hence, explicit values not specified in the calling place, default value has been taken.

static void Power(int v, int p = 2)
 Console.WriteLine("{0} Power of {1} = {2}", v, p, Math.Pow(v, p));

p is the optional parameter here. By default Power does calculate square of v, if p value provided explicitly, does calculate v to the power of p.

Power(2, 3);  // 2 ** 3 = 8
Power(4); // 4 ** 2 = 16

Actually, two parameter target attributes help to make this feature available. These are:

  • OptionalAttribute
  • DefaultParameterValueAttribute

in System.Runtime.InteropServices namespace.

The OptionalAttribute marks the parameter as optional as like

static void Power(int v, [Optional] p) {...} // p's default value is to default(int) i.e. 0

Power(5); // prints 1

The DefaultParameterValueAttribute constructor takes value parameter of type object is used to initialize the default value of the target parameter.

static void Power(int v, [Optional][DefaultParameterValue(2)] p) {...} // p's default value is 2

Points to be noted on “optional” parameter usage:

  • Optional parameter should be the last parameter as like “param” usage
  • ref and out parameters.

Named Parameters

Optional parameter will not be useful in real without named parameters. Yes, the name itself tells the answer. What will you do if you have more than one optional parameters and at the calling place, you want to pass actual value for less number of optional parameters. For example

static void MoreOptionalParamMethod(int a = 0, int b = 1, int c = 2)
 Console.WriteLine("a= {0}, b= {1}, c= {2}, ", a, b, c);

Now, you want to pass the value of variable b only. Named parameter will help you.

Instead of parameter order, you can explictly specify parameter name along with the value using “:” in the calling place

See the following calling place

MoreOptionalParamMethod(b: 5); // prints a= 0, b= 5, c= 2

There is no surprising in the IL code, the compiler replaces optional parameters with default values as like below

MoreOptionalParamMethod(0, 5, 2);

The only thing to be considered is named and normal parameters can be mixed but normal parameter should be come first.

Mark this!
  • Digg
  • del.icio.us
  • Add to favorites
  • RSS