TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
New feature "Optional parameters" in C# 4.0
Shankey
Nov 23, 2010
6.1
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
A look at the new feature "Optional parameters" in C# 4.0.
WOptionalArgument.rar.zip
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);
}
W
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:
double
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);
Next Recommended Reading
C# 4.0 New Features