C# 4.0 Optional/Named Parameters Beginner’s Tutorial

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Fri, 07 May 2010 12:17:11 GMT Indexed on 2010/05/11 2:55 UTC
Read the original article Hit count: 279

Filed under:

One of the interesting features of C# 4.0 is for both named and optional arguments.  They are often very useful together, but are quite actually two different things. 

Optional arguments gives us the ability to omit arguments to method invocations.

Named arguments allows us to specify the arguments by name instead of by position.  Code using the named parameters are often more readable than code relying on argument position.  These features were long overdue, especially in regards to COM interop.

Below, I have included some examples to help you understand them more in depth. Please remember to target the .NET 4 Framework when trying these samples.

Code Snippet
  1. using System;
  2.  
  3. namespace ConsoleApplication3
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.  
  10.             //C# 4.0 Optional/Named Parameters Tutorial
  11.  
  12.             Foo();                              //Prints to the console | Return Nothing 0
  13.             Foo("Print Something");             //Prints to the console | Print Something 0
  14.             Foo("Print Something", 1);          //Prints to the console | Print Something 1
  15.             Foo(x: "Print Something", i: 5);    //Prints to the console | Print Something 5
  16.             Foo(i: 5, x: "Print Something");    //Prints to the console | Print Something 5
  17.             Foo("Print Something", i: 5);       //Prints to the console | Print Something 5
  18.             Foo2(i3: 77);                       //Prints to the console | 77
  19.         //  Foo(x:"Print Something", 5);        //Positional parameters must come before named arguments. This will error out.
  20.             Console.Read();
  21.         }
  22.  
  23.         static void Foo(string x = "Return Nothing", int i = 0)
  24.         {
  25.             Console.WriteLine(x + " " + i + Environment.NewLine);
  26.         }
  27.  
  28.         static void Foo2(int i = 1, int i2 = 2, int i3 = 3, int i4 = 4)
  29.         {
  30.             Console.WriteLine(i3);
  31.         }
  32.     }
  33. }

© Geeks with Blogs or respective owner