Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
New feature "Optional parameters" in C# 4.0
WhatsApp
Shankey
14y
6.2
k
0
0
25
Blog
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);
Up Next
C# 4.0 New Features
Ebook Download
View all
Diving Into Microsoft .NET Entity Framework
Read by 13.3k people
Download Now!
Learn
View all
Membership not found