The world of .NET from a Connected Systems MVP & INETA Speaker

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

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 forever) but they do address some hardships in working with COM from C#. So, rather than identifying an argument by position, named parameters let you identify an argumment ny name explictly, rather than relying only on parameter order. A trivial example is as follows:

using System;
 
namespace NamedParameters
{
    class Program
    {
        static void Foo(int x, int y) 
          { Console.WriteLine(x + ", " + y); }
 
        static void Main(string[] args)
        {
            Foo(x: 4, y: 2); // 4.2
        }
    }
}
 

Named arguments can occur in any order. The following calls to foo are semantically identical:

      foo(x:4, y:2);

      foo(y:2, x:4);

You can mix named and positional parameters:

      foo(4, y:2);

However you should note that positional parameters must come before named parameters. So we couldn't do this:

     foo(x:4, 2);     // Compile time error

Named arguments are particuarly useful together with optional parameters:

     void Bar(int a = 0, int b = 0, int c = 0, int d = 0) {...}

We can then call this supplying only a value for d as follows:    Bar(d:3);

This is particuarly useful when calling COM APIs, which I'll leave out for later.

» Similar Posts

  1. C# 4.0/BCL 4 Series:Dynamic Primitive Type Part 2
  2. C# 4.0/BCL 4 Series: C# 4 Optional Parameters
  3. Windows Workflow 101 or 2 Months with WF

» Trackbacks & Pingbacks

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

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

» Comments

  1. Beezler avatar

    Sam - Great series. To be semantically equal foo(x:4, y:2); would equal foo(y:2, x:4);

    Beezler — May 20, 2010 8:16 AM
  2. samgentile avatar

    Thank you and thanks for the correction

    samgentile — May 20, 2010 10:20 AM

» Leave a Comment