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?
PS I usually prefer List<>
because of the flexibility but here the possibility to create an Array
on the fly is a good point.
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:
In this case:
IEnumerable<T>
. ICollection<T>
would be the most liberal option IList<T>
. On top of what nvoig said, I would:
public DataTable Select(string query, params string[] parameters)
{
return Select(query, (IEnumerable<string>)parameters);
}
public DataTable Select(string query, IEnumerable<string> parameters)
{
return null;
}
so that if you have a "static" query, you can use the first overload (because you know at compile time the number of parameters), while if you have a "dynamic" query you can use the second overload with a string[]
or a List<string>
or the result of a LINQ expression.
Personally, I would expect at least one overload that grants me the ability to pass a params array:
public DataTable Select(string query, params string[] parameters);
That would allow me to call it with parameters like this:
Select("SELECT FROM WHERE", "3", "17", "Joe");
Anyone having an IEnumerable<>
could pass it in easily, too:
Select("SELECT FROM WHERE", myData.ToArray());
Better would be an overload doing this for me.
In general I would use IEnumerable<T>
if you only read from the sequence.
In this particular context however I'd simply use a params string[]
or even params object[]
type since then you can use it like String.Format
, ie
var dt = Select("select A from Table where X=? and Y=?", value1, value2);
If your parameters have all the same type (here string) you can use params keyword with string array.
public DataTable Select(string query, params string[] parameters)
Thus you can call it like below
Select(myQuery, param1, param2, ...);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.