What Are Named Arguments In C#

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
  1. using System;  
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("hello Tutpoint");  

  10.             Program.Details(roll_No: 4, name: "Shubham", course: "Btech", id: 2); 
  12.             // Arguments are passed in different order  
  13.             Program.Details(name: "Rishabh", roll_No: 44, id: 1, course: "Bcom");  
  15.             Console.ReadLine();  
  16.         }  
  18.         public static void Details(int roll_No, string name, int id, string course)  
  19.         {  
  20.             Console.WriteLine(string.Format("Roll No.: {0}, Name: {1}, id: {2}, Course: {3}", roll_No, name, id, course));  
  21.         }  
  22.     }  
  23. }  
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.


We can not pass fixed arguments after specifying named arguments, this will produce an error:
  1. 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.
  1. 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:
  1. Program.Details("4", roll_No: "Shubham", course: "Btech", id: 2);