Optional parameters in C#
gpeipman
53.3K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Optional parameters
C# supports optional parameters when working with methods. Optional are parameters that have default value specified like shown in the following example. It is convenient way to write methods that have default values specified for their arguments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
class Hello
{
static void Main()
{
Console.WriteLine(SomeMethod());
Console.WriteLine(SomeMethod(null) ?? "<null>");
Console.WriteLine(SomeMethod("specified value"));
}
static string SomeMethod(string s1 = "default value")
{
return s1;
}
}
Enter to Rename, Shift+Enter to Preview
Optional parameters must be the last ones in method arguments list.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content