Defaults in C# 4.0 Method Parameters

C# 4.0 was released in April 11, 2010. By that point, C# was 8 years old and there were A LOT of developers out there that knew C# already and didn’t pay much attention to the changes and didn’t incorporate them into their current code. Many were able to keep chugging along happily doing what they had been doing without having to learn about the new features.

That’s too bad.

One of my favorite, 4.0 additions is named-arguments and optional-parameters. I think they are my favorites because of my stint as a Visual Basic programmer during my time between PowerBuilder and C#. You got used to not supplying parameters if you didn’t care to pass them or didn’t need them.

You can easily tell when a developer doesn’t know about this feature too. They tend to have a lot of overloading of a method that essentially hides parameters. And, they make calls to variants of the methods when they want to have defaults and not supply them. Or, they don’t want to have to supply them everywhere.

Their code will look something like this:

public void Broadcast(string group, int unitId) { . . . }

public void Broadcast(string group) { Broadcast(group, 5); }

public void Broadcast() { Broadcast(“Red Leader”); }

From above, you can see that the first method takes two parameters. If this were the only method, you’d have to supply defaults everywhere. So, in the event that you just want to pass the group and always default to 5 in the unitId when you do, you could just call the second routine. Or, if you want to default both parameters, you could call the third variation, which calls the second, which then calls the first. That’s a lot of pushing and popping on the stack just to have defaults.

After C# 4.0, these three methods can be collapsed into just this one method by simply using defaults. Here’s what it looks like

public class Broadcaster
{
    public static void Broadcast(string group = "Red Leader",
       int unitId = 5) { Console.WriteLine("This is {0} {1}", group, unitId); } } class Program { static void Main(string[] args) { Broadcaster.Broadcast(); Broadcaster.Broadcast(group: "Blue Leader"); Broadcaster.Broadcast(unitId: 2); } }

So, if you just wanted to supply a different unitId, you simply pass in a unitId: 6 in the method call. The group would default, and the effect is as if you called the method with the parameters “Red Leader” and 5.

Defaults make these sorts of libraries much leaner to write.

I hope this helps you.