Named parameters in C#

gpeipman
855 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Named parameters

Related to optional parameters in C# are named parameters at method calls. There are libraries with classes that have long argument lists and when calling these methods we usually have to give only the parameters we know.

The following example shows how to call method with named parameters to save time and win on readability of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
class Hello
{
static void Main()
{
SomeMethod(value2: "Second value");
}
static void SomeMethod(string value1 = "value1", string value2 = "value2", string value3 = "value3" /* etc */)
{
Console.WriteLine("value1: " + value1);
Console.WriteLine("value2: " + value2);
Console.WriteLine("value3: " + value3);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content