Search code examples
c#.netcoding-stylenamed-parameters

Passing values into methods


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?


Solution

  • 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.