Archive for May, 2010

Optional (or Default) Parameters in C# 4.0


This feature of C# has been obtained from VB.NET. In new C# 4.0 there is an option to pass all the parameters as optional and no need to unnecessarily overload the methods. This is really a great feature to be implemented in all the programming languages.

Hands on:

Prior to that we have to include the using of

using System.Runtime.InteropServices

And our functionality as follows

public void MainMethod()
       int parameter1 = 1;
       int parameter2 = 2;
       MethodCall2(parameter1,parameter2);     // This method will call MethodCall2 as usual
       MethodCall2(parameter1);                // This method will call MethodCall2 with only 1 parameter and the other is Optional
   public void MethodCall1(int x)
       // this is an example of ordinary method execution
       Console.WriteLine("MethodCall1 is executed");
   public void MethodCall2(int x, [Optional] int y)
       // This method will be called with 1 parameter and also with 2 parameters
       Console.WriteLine("MethodCall2 is executed");


Categories: SQL and .NET Blog