Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# params keyword and function overloading

In .net framework I constantly see overloaded functions like the following,

  1. public void Log(string message)...
  2. public void Log(string message, params object[] args)...

my question is since the params keyword allows zero or more parameters, could we just get rid of the first signature? With just the second signature, I could call it with no parameters fine like below, so I don't know why they would have the first signature?

Log("calling with no param");
like image 343
Ray Avatar asked Aug 11 '11 02:08

Ray


3 Answers

Another reason is params is slow, thinking that all parameters are collected and an array is built. So the second one is slower.

public static string Format(string format, object arg0);
public static string Format(string format, params object[] args);
like image 59
Cheng Chen Avatar answered Sep 30 '22 02:09

Cheng Chen


This pattern is typically used if the array-less version has a simpler implementation.

like image 29
SLaks Avatar answered Sep 30 '22 01:09

SLaks


There is a small speed advantage as well.

Milliseconds taken for 1 billion iterations of calling a very simple (count++) method with each:

  • 2472 ms w/o params
  • 7773 ms w/ params
like image 30
porges Avatar answered Sep 30 '22 00:09

porges