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

C# 4.0 New Features – Named and Optional Parameters

Rate me:
Please Sign up or sign in to vote.
4.90/5 (10 votes)
22 Mar 2010CPOL2 min read 24.4K   7   9
One of the new features in C# 4.0 – Named and Optional Parameters. Actually these are not a single feature, but two different features.

In this post, I will talk about one of the new features in C# 4.0 – Named and Optional Parameters. Actually these are not a single feature, but two different features. You can get more benefit if you work with them together. So, what are those? Named parameter is a way to provide a parameter to the method using the name of the corresponding parameter instead of its position in the parameter list. Whereas, optional parameter allows you to omit arguments to member invocation.

Let us discuss it in depth with a simple example. First, start with the Optional Parameter. Suppose you are creating a Calculator application where you have to do some “Add” operation by passing two, three or four parameters to the method. What will you do if you are using C# 2.0 or 3.0? You will have no other choice than creating as many methods and passing the parameters in this which is known as method overloading.

C#
public int Add(int a, int b);
public int Add(int a, int b, int c);
public int Add(int a, int b, int c, int d);

If you are using C# 4.0, just forget about method overloading by using the optional parameter. Optional parameter is a default value passed to the method signature. Let us go for modifying our previous example to use optional parameter.

C#
public int Add(int a, int b, int c = 0, int d = 0);

Here, we are passing default values to the parameters “c” and “d”. Hence, you can call this method as per your requirement like this:

C#
Add(10, 20); // 10 + 20 + 0 + 0
Add(10, 20, 30); // 10 + 20 + 30 + 0
Add(10, 20, 30, 40); // 10 + 20 + 30 + 40

In the first case, it will pass ‘0’ (zero) as the optional parameter c and d, in the second case, the fourth parameter will be treated as ‘0’ (zero) and in the third case all the parameters are available with proper values.

Now, let us think that we have a situation where we are creating an account of a user with the method named “CreateAccount” which has a non-optional parameter “Name” and two optional parameters “Address” & “Age”. Here in some scenario, you want to pass only the “Name” and “Age”, how can you pass them? Just think about it.

C#
public void CreateAccount(string name, string address = "unknown", int age = 0);

Are you thinking of calling the method with an empty string or null value to the “Address” parameter? Oh, not really. There comes another new feature of C# 4.0 called as “Named Parameter”. Using this, you can call the method with proper name resolution or even you can change the position of the parameter while calling the method. Have a look into the following code example:

C#
CreateAccount("Kunal", age: 28);
CreateAccount(address: "India", name: "Kunal");

The first example shows calling the method without the middle parameter “Address” and the second example demonstrates calling the same method after changing the position of the parameter in the parameter list using the name of the parameter. In this way, you can create a single method with Named & Optional Parameter instead of overloading it several times and use it everywhere you need as per your requirement. This gives more cleaner code with less efforts. Enjoy working with this. Cheers!

This article was originally posted at http://kunal2383.blogspot.com/feeds/posts/default

License

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


Written By
Technical Lead
India India

Kunal Chowdhury is a former Microsoft "Windows Platform Development" MVP (Most Valuable Professional, 2010 - 2018), a Codeproject Mentor, Speaker in various Microsoft events, Author, passionate Blogger and a Senior Technical Lead by profession.

He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows app development. He posts his findings, articles, tutorials in his technical blog (www.kunal-chowdhury.com) and CodeProject.


Books authored:


Connect with Kunal on:





Comments and Discussions

 
GeneralMy vote of 5 Pin
aamarnathshetty31-Aug-12 2:06
aamarnathshetty31-Aug-12 2:06 
GeneralGood one Pin
thatraja29-Jan-12 9:39
professionalthatraja29-Jan-12 9:39 
GeneralSimple, but good Pin
Chad Strawinski30-Mar-10 5:19
Chad Strawinski30-Mar-10 5:19 
GeneralRe: Simple, but good Pin
Kunal Chowdhury «IN»30-Mar-10 5:26
professionalKunal Chowdhury «IN»30-Mar-10 5:26 
GeneralMy vote of 3ish Pin
EngleA30-Mar-10 3:32
EngleA30-Mar-10 3:32 
GeneralRe: My vote of 3ish Pin
Kunal Chowdhury «IN»30-Mar-10 4:47
professionalKunal Chowdhury «IN»30-Mar-10 4:47 
Hi EngleA,

First of all, thanks for your feedbacks. I am happy to hear that, you learnt something from this post.
Now for your other context of comment:

EngleA wrote:
I don't think the "add" example is a very good one. 


I know that, this is not a very good example for doing a job on calculator, but it is a very basic example you should do while learning something new. My post is targeted for both the beginner in .Net (C#) and the experts who want to learn the new feature of C# 4.0. If you try with a real complex scenario while learning the basic, is it a good idea?

EngleA wrote:
BUT, I understand the example to demonstrate optional parameters.


Exactly the same thing I wanted to convey to my reader, you must understand the basic instead of doing a huge brainwork to understand. Am I right?

EngleA wrote:
But for your human resources example, it's ineffective and completely backwards in the world of OOP.   If your using this example in the Enterprise, I'd fire you.   Creating a method like AddEmployee(string name, string address, string city, string state, string zip, string phone, string gender, string....) is just plain stupid.      AddEmployee(Employee emp) is a much better way.    THIS is where named parameters may hit a high note...naming custom objects to be passed into the method or something like that.


Though in most of the cases in real world of OOPs it is not require, but there comes some scenarios when method overloading we have to use. In that case, you don't have other choice than that. Whether it is a basic example for learner or an Enterprise example, you need to overload your methods (for various reasons). Just imagine various methods in-built in .Net framework which has method overloading. In those scenarios you can use Named & Optional parameters instead of writing a huge code to implement method overloading.

EngleA wrote:
If your using this example in the Enterprise, I'd fire you.


If that is the case, then all the programmers will lose their jobs, mainly who developed .Net framework itself. Poke tongue | ;-P

EngleA wrote:
Interesting though.   I had not heard of either of these features until i read your article.

My vote is based on your examples only.   good article...it's readable (most here aren't) and I got the jist of what you were saying and learned something.


Again, thanks for reading and learning about the new features from my article. I hope, in future this will help you in real scenarios. And at that time, you will give a big thank to Microsoft. Shucks | :-\
Regards - Kunal Chowdhury | Software Developer | Chennai | India | My Blog | My Tweets

GeneralTrue power Pin
NickThissen22-Mar-10 11:14
NickThissen22-Mar-10 11:14 
GeneralRe: True power Pin
mathomp330-Mar-10 2:30
mathomp330-Mar-10 2:30 
GeneralRe: True power Pin
Kunal Chowdhury «IN»30-Mar-10 4:25
professionalKunal Chowdhury «IN»30-Mar-10 4:25 

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.