Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# function parameter Array vs List

I'm writing a simple C# class that handle SQL queries in a specific contest. Most of the queries will be SELECT statement with 3-4 parameters that should be escaped properly, so the function will be something like this

public DataTable Select(string query, string[] parameters) {
    # some code
}

Should parameters be an Array or a List<>? Is there some best practice when choosing between these two types as function parameter or is it just a matter of preferences?

P.S. I usually prefer List<> because of the flexibility but here the possibility to create an Array on the fly is a good point.

like image 864
Naigel Avatar asked Nov 28 '22 23:11

Naigel


2 Answers

You should use IEnumerable, then it can be either since both list and array implement this

public DataTable Select(string query, IEnumerable<string> parameters)

They also both implement IList and ICollection, which may offer other useful properties as shown by Tim Schmelter in the comments

like image 198
Sayse Avatar answered Dec 05 '22 21:12

Sayse


According to the Robustness principle, or Postel's law (emphasis mine):

Be conservative in what you do, be liberal in what you accept from others

In other words, use the "broadest" type possible, the one higher up in the inheritance hierarchy, so as to:

  1. demand as little as possible from the user,
  2. and give the user as many choices as possible.

In this case:

  • if all you need to do is iterate through the collection of parameters, then you should demand from the user an instance of a type that can be iterated: which, in this case, is IEnumerable<T>.
  • If you needed to add/remove items, then ICollection<T> would be the most liberal option
  • If, for some reason, you need to access items by index, then you should demand a IList<T>.
like image 45
dcastro Avatar answered Dec 05 '22 21:12

dcastro