In this blog, I will demonstrate how to use Named Arguments in C#.
Named Arguments
Generally, In Methods call, arguments are passed according to the order of parameters defined in the method definition. So, when making a method call, it is necessary for us to remember the order of parameters before passing the value to the method call. If the number of parameters is large, then it is difficult to remember the order.
To overcome this, Named arguments are used. When calling a method, arguments are passed with the parameter name followed by a colon and a value. In Named Arguments, we do not need to pass the parameters in order as defined on method definition, so we can pass the arguments in any order on method calling.
Example of Named Arguments
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("hello Tutpoint");
- Program.Details(roll_No: 4, name: "Shubham", course: "Btech", id: 2);
-
-
- Program.Details(name: "Rishabh", roll_No: 44, id: 1, course: "Bcom");
-
- Console.ReadLine();
- }
-
- public static void Details(int roll_No, string name, int id, string course)
- {
- Console.WriteLine(string.Format("Roll No.: {0}, Name: {1}, id: {2}, Course: {3}", roll_No, name, id, course));
- }
- }
- }
Here, Details() is a method that contains 4 parameters as (roll_No, name, id, course). On method call, arguments use the name of the parameter followed by a colon and the value. Arguments can be passed in any order.
Note
We can not pass fixed arguments after specifying named arguments, this will produce an error:
- Program.Details(roll_No:2,name: "Mohit", id:2,"Art");
Here, "Art" is the fixed argument which is used after specifying named arguments(roll_No, name, id). This is incorrect and produces an error as 'Named argument specifications must appear after all fixed arguments have been specified'.
But, we can specify fixed arguments before specifying named arguments in order, as shown below.
- Program.Details(4, name: "Gaurav", course: "BArch", id: 22);
If the order of the fixed arguments passed is incorrect, then it will produce an error as 'Named argument 'roll_No' specifies a parameter for which a positional argument has already been given:
- Program.Details("4", roll_No: "Shubham", course: "Btech", id: 2);