As I understand it, params
is just syntactic sugar that "under the hood" simply gives you an array of the type you specify.
First, when would you use this?
Second, why would you use it instead of just declaring an array argument?
As I understand it, params
is just syntactic sugar that "under the hood" simply gives you an array of the type you specify.
First, when would you use this?
Second, why would you use it instead of just declaring an array argument?
Math.Min
takes exactly two arguments. This is a stupid limitation. Many other languages allow you to write:
double x, y, z, w;
double least = min(x, y, z, w);
If you wanted to write a min
function that could be used like that, you'd want to use params
.
An obvious example can be found in a method like String.Format()
. This statement using params is easy to follow:
string.Format("Your name is {0}, {1}", lastName, firstName);
But without params it's a bit more difficult:
string.Format("Your name is {0}, {1}", new string[] { lastName, firstName });
I find myself using params alot for string functions like these. I use it just to improve the readability of the code.
void LogInformation(Type objectType, string methodName, string message, params object[] args)
. So then I can just say Logger.LogInformation(myType, "method", "{0} called by {1}", "somevalue", "someothervalue");
–
Morissa One way that I used it is in passing sql queries off to my wrapper class. I'll have some sql with a variable number of parameters in it. This way I can just list all of the parameters I'm sending with the query rather than creating an array first.
SQLWrapper.Query(" some sql with parameters", new SqlParameter("@param1", val1),
new SqlParameter("@param1", val1),
new SqlParameter("@param1", val1));
Much nicer than the alternative:
SQLWr
apper.Query(" some sql with parameters", new SqlParameter[]{new SqlParameter("@param1", val1),
new SqlParameter("@param1", val1),
new SqlParameter("@param1", val1)});
Its nice to have when you run into a situation where you need a variable number of arguments.
An example from the Base Class library is String.Split(params char[] separator)
, allowing you to write, for example:
var segs = myString.Split(',',';',' ');
rather than
var sets = myString.Split(new char[] {',', ';', ' '});
The main non-prettier / easier to understand reason I find myself using params is in executing stored procedures.
Take the case where you have several hundred stored procedures in a database. Then you really only have two choices
1: Write code individually for each stored procedure which would take months
2: Create a generic executor method which will run any stored procedure and take any number & type of parameters e.g.
databaseHelper.ExecuteStoredProcedure(
"myStoredProecdure",
DbProviderHelper.StringParameter("@parameter_string", somestring),
DbProviderHelper.BoolParameter("@parameter_string", somebool),
DbProviderHelper.IntParameter("@parameter_int", someint));
© 2022 - 2024 — McMap. All rights reserved.