C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: You can reorder these named parameters in any way you want. This is a key benefit of named parameters.
Also: You can specify names on only some parameters, using the positional syntax for some arguments.
C# program that uses named parameters
using System;
class Program
{
static void Main()
{
// Call the Test method several times in different ways.
Test(name: "Perl", size: 5);
Test(name: "Dot", size: -1);
Test(6, "Net");
Test(7, name: "Google");
}
static void Test(int size, string name)
{
Console.WriteLine("Size = {0}, Name = {1}", size, name);
}
}
Output
Size = 5, Name = Perl
Size = -1, Name = Dot
Size = 6, Name = Net
Size = 7, Name = Google
Version 1: This version of the code uses a method invocation with named parameter syntax.
Version 2: This version uses position parameters (not named parameters) to call the same method as version 1.
Result: In 2019, no difference was found between the 2 calling syntax forms. Named parameters are fast.
Note: Please disregard the logic of Method3 as it is there mainly to ensure the method is not inlined.
C# program that tests named parameter performance
using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
Method1();
Method2();
var s1 = Stopwatch.StartNew();
// Version 1: use named parameters.
for (int i = 0; i < _max; i++)
{
Method1();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use positional parameters.
for (int i = 0; i < _max; i++)
{
Method2();
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
_max).ToString("0.00 ns"));
Console.Read();
}
static void Method1()
{
Method3(flag: true, size: 1, name: "Perl");
}
static void Method2()
{
Method3(1, "Perl", true);
}
static void Method3(int size, string name, bool flag)
{
if (!flag && size != -1 && name != null)
{
throw new Exception();
}
}
}
Output
0.28 ns [named parameters]
0.28 ns
And: It then reorders those locals in the argument slots. For named parameters, the compiler infers the regular order from the new syntax.