Caveman's Blog

My commitment to learning.

Posts Tagged ‘Optional Parameters

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:


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);

Written by cavemansblog

December 20, 2011 at 1:55 pm