Named Arguments in .Net 4.0
If I would pass the arguments to the method in some other sequence it would give error.
But a positional argument cannot follow a named argument, as shown below:
A new feature has been introduced in .Net 4.0 which is of immense use for coders. The feature is Named Arguments. To understand what does it do first I would create a scenario which would help better understand the need of Named Arguments.
Often when we write methods implementing a logic we require some input parameters. These parameters are passed to the method. Now the problem is that the sequence in which the parameters are to be passed to the method should be same as the sequence in which the arguments are defined in the method signature.
Class MyClass
{
public void MyMethod(int id, string name, double salary, string department)
{
.......
}
}
{
public void MyMethod(int id, string name, double salary, string department)
{
.......
}
}
So if I want to call this method I have to pass the arguments in the same sequence as defined in the method signature.
MyClass obj = new MyClass();
obj.MyMethod(100, "Jai", 7500, "Software");
obj.MyMethod(100, "Jai", 7500, "Software");
If I would pass the arguments to the method in some other sequence it would give error.
obj.MyMethod(100, "Jai", "Software", 7500); //compiler error as parameters are in wrong sequence
Further many a times we make methods that have many arguments and it is difficult to remember their sequence. This often leads to compile time errors and a headache for the developer !
To overcome this .Net 4.0 has come up with a new feature viz. Named Arguments. They enable you to call the method and pass the parameters in any order. All we need to do is to specify the parameter name for each argument. The following example will make it clear:
obj.MyMethod(name: "Jai", department: "Software", salary: 7500, id: 100);
Here I have given the argument name along with its value. This is the way to implement Named Arguments. The sequence of the arguments as defined in the method signature does not matter any more. Another advantage is that is improve the readability of the code by identifying what each argument represents.
There is a constraint in Named Arguments also. A named argument can follow positional argument, as shown below:
obj.MyMethod(100, "Jai", department: "Software", salary: 7500);
Here first two parameters as passed in exact position (i.e. positional argument), but the other two are passed as Named Argument.
But a positional argument cannot follow a named argument, as shown below:
obj.MyMethod(name: "Jai", salary: 7500, id: 100, "Software");
Here the last parameter is in exact position (i.e. positional parameter) but the other three are passed as Named Argument. This is not allowed and the compiler will show an error.
Hi sir,
ReplyDeleteExecellent post very easily understandable.
Thanq