What's new in Visual C# 4.0 ? - Part 2 - Names Parameters

This is the second post of what’s new in Visual Studio C# 4.0.

At the former post we reviewed the feature of optional parameters at this post we will concentrate on Named Parameters.

Named Parameters

Lets assume you are writing the following procedure :

  1. public static void SaySomething(string name, string msg)
  2.         {
  3.             Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
  4.         }

When you want to call it from your code you are using something like:

Code Snippet
  1. static void Main(string[] args)
  2.         {
  3.             SaySomething("Ohad","What's up?");
  4.             Console.ReadLine();
  5.         }

What’s the problem ?

Although you will have intellisense while you are coding it for the reader of the code its unclear what is the first parameter and what is the second parameter.

This is where Named Parameters gets into the picture. Using named parameter the code becomes much more readable to one who haven’t wrote it.

Code Snippet
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             SaySomething(name: "Ohad", msg: "What's up?");
  6.             Console.ReadLine();
  7.         }
  8.         public static void SaySomething(string name, string msg)
  9.         {
  10.             Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
  11.         }
  12.     }

Named parameters are specially useful whenever you have multiple optional parameters of the same type. Without using named parameter how would the compiler know if the parameter which is being passed by line 5 is the name or the message.

Code Snippet
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             SaySomething(name: "Ohad");
  6.             Console.ReadLine();
  7.         }
  8.         public static void SaySomething(string name = "Tirza", string msg = "Hi There")
  9.         {
  10.             Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
  11.         }
  12.     }

No Comments