So let's say you have:
public void TestFishsticks()
{
var fishes = GetFishstick(false);
}
private object GetFishstick(bool getBigFishes)
{
return FishsticksManager().GetFishsticks(getBigFishes);
}
vs
public void TestFishsticks()
{
var fishes = GetFishstick(getBigFishes: false);
}
private object GetFishstick(bool getBigFishes)
{
return FishsticksManager().GetFishsticks(getBigFishes);
}
Is there any reason for this?
In my current companies codebase we seem to do both, but there seems to be no reason for one over the other. I could see a small readability improvement with the second choice, because you get to see the parameter name straight away, but you can see it via intellisense anyway?
Named arguments have mainly been introduced in C# 4.0 to improve readability. You don't actually have to use them. Some people prefer using them in some cases, others don't. It's basically up to you.
It can greatly improve readability, especially when you don't want to trigger intellisense when reading code all the time (or even worse, reviewing print-outs). Compare these two:
CalculateBMI(123, 178); // What do the numbers mean?
CalculateBMI(weightInKg: 123, heightInCentimeters: 178); // Clearer IMHO.
However, using named arguments and optional parameters together enables you to supply arguments for only a few parameters from a list of optional parameters. This capability for instance greatly facilitates calls to COM interfaces.
there seems to be no reason for one over the other
Some good reasons to use named arguments:
The code is easier to understand at a glance, particularly when the argument is false or null or 0 or "" and so on.
Named arguments work well with optional arguments. A method that takes a dozen arguments can have a simplified call site if you just need to specify a few of them.
The code is robust in the face of reordering refactorings during early development. If you make a breaking change before releasing to customers, changing:
void M(int width, int height)
to
void M(int height, int width)
then all the code that said
M(height: 123, width: 456);
will still be correct, but the code that said
M(123, 456);
will need to be updated.
Similarly, this makes code robust in the face of changing this method that specifies a rectangle:
M(int top, int bottom, int left, int right)
to this method:
M(int top, int height, int left, int width)
an obvious breaking change. Code
M(top: 10, bottom: 20, left: 30, width: 40)
will give an error when the method changes. This code will not, and changes behaviour:
M(10, 20, 30, 40);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With