If you find this article useful, consider making a small donation to show your support for this web site and its content.
DiscountASP
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.

Named and optional parameters in C# 4.0

by Farooq Kaiser 6. August 2009 05:14

In this article, I will explore named and optional parameters in C# 4.0 features. Named and optional parameters are really two distinct features, and allow us to either omit parameters which have a defined default value, and/or to pass parameters by name rather than position. Named parameters are passed by name instead of relying on its position in the parameter list, whereas optional parameters allow us to omit arguments to member without having to define a specific overload matching.

Let’s have a look at Optional parameters.

//In old way we will write the code as shown below. 
  public static double MyOldCurrencyExchange(double amount, double rate) 
  { 
    return (amount * rate); 
  } 
 //We will call the above method as shown below. 
  MyOldCurrencyExchange(500, 1.18); 
//Now, by using optional parameters 
//In new way we will write the code as shown below. 
  public static double MyNewCurrencyExchange(double amount, double rate=1) 
  { 
    return (amount * rate); 
  } 
 //We will call the above method as shown below. 
  MyNewCurrencyExchange (500, 1.18);  // ordinary call 
  MyNewCurrencyExchange (500);  // omitting rate 
 //Now, by using Named parameters 
 MyNewCurrencyExchange (rate:1.18, amount:500); // reversing the order of arguments.Now, by using Named and optional parameters 
 MyNewCurrencyExchange (amount:500); 

Summary 

In this article, we explored C# 4.0’s new feature Named and optional parameters and I will continue to explore C# 4's features in the next article.

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

.NET | C#

Comments

Jobs Autos Real estate Videos Power by Google