Object-Oriented Programming – Why Methods with Unlimited Parameters Define Overloads

method-overloadingobject-orientedparameters

For instance, the System.IO.Path.Combine method in .NET has the following overloads:

Combine(params String[])
Combine(String, String)
Combine(String, String, String)
Combine(String, String, String, String)

What is the point of the last three?

The first one would cover them all, as if you look closely, it uses the params keyword. The argument of backwards compatibility would only cover the Combine(String, String) variant, as it was the only version until .NET 4.

Best Answer

The main reason is for performance. The "unlimited arguments" syntactical sugar is actually an array of Strings. If you are only passing one string, why create an array with only one string? Especially if ~90% of the invocations of this method will be with 3 or fewer arguments, there is no need for the heavier weight array object. It's a little lighter in memory and takes a little less processing time because you don't need a loop in order to define the method. If you have three strings, you just code for three strings.

Related Topic