Click here to Skip to main content
15,884,425 members
Articles / Programming Languages / C#
Tip/Trick

Named Parameter Feature Of C#.NET 4.0

Rate me:
Please Sign up or sign in to vote.
3.83/5 (5 votes)
19 May 2012CPOL 15.4K   5
Named parameter feature of C#.NET 4.0

Introduction

Named parameter is the feature provided by .NET Framework 4.0 to get us rid from the headache of remembering sequence or order of parameters passed in any method. Here one can specify parameter name with each argument, which makes the programming task easy. This allows one to explicitly name an argument that is being passed, instead of just identifying it by position of argument.

Background

Let's assume your constructor definition looks like this:

C#
public Employee(string firstName, string lastName, DateTime dateOfBirth) 

In that case, one has no other option till framework 3.0 other than to invoke the constructor like this:

C#
Employee employee = new Employee("Shweta", "Jain", new DateTime(1990,1,1)); 

So, now in this case, it is not clear about what is being assigned in the constructor (i.e. that third DateTime parameter might be date of birth, might be date hired, who knows).

Using the Code

In Framework 4.0, one can invoke the constructor like this:

C#
Employee employee = new Employee(firstName: "Shweta", 
lastName: "Jain", dateOfBirth: new DateTime(1990,1,1);   

Points of Interest

This expresses the intent clearly and makes the code more understandable.

To get more interesting information, follow this link.

License

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



Comments and Discussions

 
GeneralMy vote of 4 Pin
honeysinghi23-May-12 17:16
honeysinghi23-May-12 17:16 
SuggestionCaution: this may be a trap! Pin
Andreas Gieriet20-May-12 9:34
professionalAndreas Gieriet20-May-12 9:34 
GeneralRe: Caution: this may be a trap! Pin
springy7622-May-12 5:14
springy7622-May-12 5:14 
BTW: Public constants suffer the same problem.
GeneralRe: Caution: this may be a trap! Pin
Andreas Gieriet22-May-12 5:21
professionalAndreas Gieriet22-May-12 5:21 
GeneralRe: Caution: this may be a trap! Pin
Shweta Lodha24-May-12 17:27
Shweta Lodha24-May-12 17:27 

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.