There are a number of examples in the .NET framework where there are multiple overloads for a method, some of which use a specific number of parameters followed by a final "catch all" where the params
keyword is used. Common examples of this are on the String
class e.g.:
I was wondering if there is a particular reason for why there are so many of these method overloads? At first I thought it might be something to do with performance; the question and answers to this SO question - Cost of using params in C# - would suggest so.
However, I started to delve into the .NET source code using the Reference Source website. I noticed this in the String class source code:
String.Concat()
actually runs different code depending on how many fixed arguments are used - this in my mind would definitely be an optimization. String.Format()
however just seems to provide wrappers around the main param
method - see below for the paraphrased code:
public static String Format(String format, Object arg0)
{
return Format(format, new Object[] { arg0 });
}
public static String Format(String format, Object arg0, Object arg1)
{
return Format(format, new Object[] { arg0, arg1 });
}
public static String Format(String format, Object arg0, Object arg1, Object arg2)
{
return Format(format, new Object[] { arg0, arg1, arg2 });
}
public static String Format(String format, params Object[] args)
{
// Do work here...
}
So are there performance benefits or can this simply be a matter of convenience, or maybe both? In the particular case above I do not see any obvious benefit and it just seems to duplicate work.
String.Format
wrappers seem to violate the .NET Framework Design Guidelines, which state: "CONSIDER providing special overloads and code paths for calls with a small number of arguments in extremely performance-sensitive APIs. This makes it possible to avoid creating array objects when the API is called with a small number of arguments. ... You should only do this if you are going to special-case the entire code path, not just create an array and call the more general method." – Velaparams
version and the other overloads kept for compatibility reasons (removing overloads would be a very breaking change) – Numberlessstring.Format
creates a struct not an array for call to format with only 1 2 or 3 arguments. This is exactly what the guideline states. "not just the array". Most likely the struct outperforms the array. – Ribbonwood