Caveman's Blog

My commitment to learning.

C# 4.0 – Named and Optional parameters

leave a comment »


In this post I will cover two C# 4.0 features that I have recently learned. Optional parameters allows us to define default values to a method parameters. This will help us calling the methods in a polymorphic manner. The code below defines a method to calculate the interest for a given principal amount:

public static decimal SimpleInterest(decimal principal, decimal interest = 2)
{
decimal interestPaid = principal * (interest / 100);
return interestPaid;
}

We can pass the principle amount and the interest rate as arguments compute the interest like below;

SimpleInterest(1000, 20);

or we can also compute the interest using the default interest rate like below:

SimpleInterest(1000);

Named arguments allows us to explicitly name the parameters that are passed to a method. This is a great feature in combination with Optional parameters when the method supports multiple optional parameters. This style of notation will make the code more readable and will be useful when  I will use the method from the above example here as well to name the arguments to the method like below:

SimpleInterest(principal : 1000, interest: 20);
SimpleInterest(principal : 1000);
Advertisements

Written by cavemansblog

December 20, 2011 at 1:55 pm

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: