In C# - Optional parameters - creates a completion to the other un-supplied parameters.
so if I write:
void Go(int a, bool isFalse = true)
and call Go(a)
it actually emit il code for Go(a, true)
.
What about named parameters and how does switching the order thing works behind the scenes?
for example :
Go(isFalse:true, a:1) //order has been switched.
When you call Go(a)
it calls Go(a, true)
not Go(a, false)
. For example;
using System;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
Go(5);
}
static void Go(int a, bool isFalse = true)
{
Console.WriteLine("Int is {0}, Boolean is {1}", a, isFalse);
}
}
}
Output is:
Int is 5, Boolean is True
You are setting isFalse
value to true
if it isn't used when its called. But if you care about orders you must use which order do you describe in your method. For example;
If you have a method like
SomeMethod(bool isFalse, bool isFull, bool isStacked)
and when you call this method like
SomeMethod(true, false, true)
your method works like
isFalse = true
, isFull = false
and isStacked = true
because of the order. But sometimes when your method has a lot of parameters which you can mix the order, you can use named parameters came with C# 4.0
. Which based same method, you can it like this;
SomeMethod(isStacked: true, isFull: false, isFalse = true)
is equal call to
SomeMethod(true, false, true)