.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

New feature Optional parameters in C# 4.0

Posted By:shankey       Posted Date: January 29, 2011    Points: 75    Category: C#    URL: http://www.dotnetspark.com  

New feature Optional parameters in C# 4.0 with an example to show how to use ptional parameters

This new feature of c# 4.0 allows uses to define optional parameter for the methods. With this new feature user can call method by passing only necessary parameters and rest of the unnecessary parameters can be omitted. But the unnecessary parameters should be declared as optional as shown below i.e. by providing default value:

//by default calculates the square of x
static double CalculatePower(double x, double n=2)
    return Math.Pow(x,n);

hen you write this method in vs2005/2008 you will get following error:


In the above CalculatePower method the default value for parameter n Is 2. When user calls this method only with one parameter then the n will hold the default value i.e. 2. Thus by default above method calculates the square of x other wise n to the power of x.
Following is the sample main program which calls this method:

x = 2;
double n = 3;
double result=  CalculatePower(x);// calculates the square of x
Console.WriteLine("Result is :{0}", result);
result = CalculatePower(x,n); // calculates the n to the power of x
Console.WriteLine("Result is :{0}", result);
 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend