Home > SQL and .NET Blog > Optional (or Default) Parameters in C# 4.0

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;
 
 
       MethodCall1(parameter1);
 
       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");
   }

-Yuva

http://Yuvahere.com

Advertisements
Categories: SQL and .NET Blog
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: