How to use named parameters in C#?
In C#, using named parameters allows passing parameter values by specifying the name of the parameter, without having to pass values in the order defined by the parameters. This can improve the readability and usability of the code.
Here is an example using named parameters:
using System;
class Program
{
static void Main(string[] args)
{
PrintInfo(name: "Alice", age: 25, city: "New York");
}
static void PrintInfo(string name, int age, string city)
{
Console.WriteLine($"Name: {name}, Age: {age}, City: {city}");
}
}
In the example above, we passed parameter values to the PrintInfo method using named parameters, allowing us to pass them in any order instead of following the order in which the method is defined. This makes the code easier to read and less prone to errors.