I was browsing through the documentation and noticed that Console.WriteLine()
method had several overloads. Particularly, my curiosity and partial confusion pertains to these:
public static void WriteLine(string format, params object[] arg); public static void WriteLine(string format, object arg0); public static void WriteLine(string format, object arg0, object arg1); public static void WriteLine(string format, object arg0, object arg1, object arg2); public static void WriteLine(string format, object arg0, object arg1, object arg2, object arg3);
It seems redundant. What is the need of the other four overloads on top of the first one? The first method is able to do everything that the other methods can do. Is there a performance concern that they were trying to tackle by providing additional overloads, which handle up to four arguments (last one)? Is the overhead of going through an array of up to four arguments large enough to provide the need for these overloads?
WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
While Write() and WriteLine() both are the Console Class methods. The only difference between the Write() and WriteLine() is that Console. Write is used to print data without printing the new line, while Console. WriteLine is used to print data along with printing the new line.
WriteLine has an impact on the performance of your specific application is profiling it. Otherwise it's premature optimization. Show activity on this post. If it's for debugging purpose, you should rather use: Debug.
So, if you're talking about System. Console. WriteLine in both cases, there's no difference.
In general you are correct that the first overload can suffice for the other overloads. This is not strictly true though because the params
keyword can't be used for indirect cases like method group binding. For example
delegate void E(string format, object o1); E e = Console.WriteLine;
The params
overload won't satisfy this case, it will only work when this particular overload is present
public static void WriteLine(string format, object arg0);
That's a pretty esoteric case though. The more important reasons are the following
params
keyword. Having the overloads reduces the burden on those languages by removing the need to manually create an array for a simple WriteLine` callparams
overload forces the caller to allocate an array, even if it's done implicitly by the compiler. Allocations are cheap in .Net but not free. Little things like this add up quickly especially on commonly called methods like Console.WriteLine
. Having the other overloads allows for the common cases to avoid this allocation 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