What's new in Visual C# 4.0 ? - Part 1 - Optional parameters

This is the first blog from a series of blog post which I'm planning to do on whet’s new in Visual C# 4.0

Optional parameters

Optional parameters is a new feature in C# 4.0 which will let you set a default value for an argument of a method. In case that the collie of the method will omit the argument the default value will take its place.

So instead of writing the following code:

  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             SaySomething();
  6.             SaySomething("Ohad");
  7.             Console.ReadLine();
  8.         }
  9.         public static void SaySomething()
  10.         {
  11.             Console.WriteLine("Hi !");
  12.         }
  13.         public static void SaySomething(string name)
  14.         {
  15.             Console.WriteLine(string.Format("Hi {0}!",name));
  16.         }
  17.     }

You will only have to write:

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

 

 

The statement name = “” at line 11 does the trick of the optional parameter with passing and empty string as the optional parameter.

Note that some of the reader of this post my think that its better to use string.Empty instead of double quote “” as it normally do but :

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

using string,Empty will result with a compilation error:

“Default parameter value for 'name' must be a compile-time constant”

And as it string.Empty is not a literal.

No Comments