What are named parameters in C#?

CsharpServer Side ProgrammingProgramming

Named parameters provides us the relaxation to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name.

NamedParameterFunction(firstName: "Hello", lastName: "World")

Using named parameters in C#, we can put any parameter in any sequence as long as the name is there. The right parameter value based on their names will be mapped to the right variable. The parameters name must match with the method definition parameter names. Named arguments also improve the readability of our code by identifying what each argument represents.

Example

 Live Demo

using System;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         NamedParameterFunction("James", "Bond");
         NamedParameterFunction(firstName:"Mark", lastName:"Wood");
         NamedParameterFunction(lastName: "Federer", firstName: "Roger");
         Console.ReadLine();
      }
      public static void NamedParameterFunction(string firstName, string lastName){
         Console.WriteLine($"FullName: {firstName} {lastName}");
      }
   }
}

Output

The output of the above code is

FullName: James Bond
FullName: Mark Wood
FullName: Roger Federer

In the above code NamedParameterFunction(lastName: "Federer", firstName: "Roger") even though parameters are not passed in order since we are using named parameters, the parameters are mapped based on the name. So we are getting the output "Roger Federer" which is as expected.

raja
Published on 04-Aug-2020 07:27:21
Advertisements