The world of .NET and Web Programming

C# 4.0/BCL 4 Series: C# 4 Optional Parameters

This is part of a series.  C# 4 allows you to declare optional parameters in methods, constructors, and indexers. A parameter is optional if it specifies a default value in its declaration:

     void Foo(int x = 42) { Console.WriteLine(x); }

Optional parameters may be omitted when calling the method:

      Foo();      // 42

The default argument of 42 is actually passed to the optional parameter x - the compiler bakes the value 42 into the compiled code at the calling side. The previous call to Foo is semantically identical to:

      Foo(42);

because the compiler simply substitutes the default value of an optional parameter whenever it is used. The default value of an optional parameter must be specified by a constant expression. Optional parameters cannot be marked with ref or out.

Mandatory parameters must occur before optional parameters in both the method declaration and the method call. In the following example, the explicit value of 1 is passed to x and the default value of 0 is passed to y:

     void Foo(int x = 0, int y = 0) {Console.WriteLine(x + "," + y);  }

     void Test()

     {

          Foo(1);             // 1, 0

     }

» Similar Posts

  1. C# 4.0/BCL 4 Series: C# 4 Named Parameters
  2. C# 4.0/BCL 4 Series:Dynamic Primitive Type Part 2
  3. C# 4.0/BCL 4 Series:Dynamic Primitive Type Part 1

» Trackbacks & Pingbacks

  1. Pingback from C# 4.0/BCL 4: What's New Series : Sam Gentile's Blog (if (DeveloperTask == Communication && OS == Windows)

  2. This is part of a series . I really should have combined Named Parameters when I wrote about Optional Parameters last time since they are similar and go well together. Again, nothing thrilling here to speak about in C# 4 (especially since VB has had these

Trackback link for this post:
http://samgentile.com/Web/trackback.ashx?id=1909

» Comments

    There are no comments. Kick things off by filling out the form below.

» Leave a Comment