Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C# 4.0

Named and optional parameters in C# 4.0

Rate me:
Please Sign up or sign in to vote.
3.58/5 (19 votes)
16 Aug 2009CPOL 76.6K   9   5
In this article, I will explore named and optional parameters in C# 4.0.

Introduction

In this article, I will explore named and optional parameters in C# 4.0. 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 members without having to define a specific overload matching.

Let’s have a look at Optional parameters:

C#
//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:

C#
MyOldCurrencyExchange(500, 1.18);

Now, by using Optional parameters:

C#
//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:

C#
MyNewCurrencyExchange (500, 1.18);  // ordinary call 
MyNewCurrencyExchange (500);  // omitting rate

Now, by using Named parameters:

C#
MyNewCurrencyExchange (rate:1.18, amount:500); // reversing the order of arguments.

Now, by using Named and Optional parameters:

C#
MyNewCurrencyExchange (amount:500);

Summary

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
BillWoodruff29-Dec-14 3:28
professionalBillWoodruff29-Dec-14 3:28 
GeneralMy vote of 5 Pin
ThatsAlok6-Feb-14 22:19
ThatsAlok6-Feb-14 22:19 
GeneralMy vote of 1 Pin
Member 429338430-Oct-12 8:40
Member 429338430-Oct-12 8:40 
GeneralVote 4 Pin
WillemToerien17-Aug-09 0:25
WillemToerien17-Aug-09 0:25 
GeneralRe: Vote 4 Pin
Govindaraj Rangaraj20-May-14 22:42
Govindaraj Rangaraj20-May-14 22:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.