What is a real example of when to use params as a method argument?
Asked Answered
M

5

5

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?

Marv answered 28/4, 2011 at 17:35 Comment(3)
"why would you use it instead of just declaring an array argument?" Syntactic sugar. That's the whole point, isn't it?Orsa
Taken to the extreme, why write in a high level language when it's all just syntactic sugar? We should just write our programs in binary.Gasbag
@Orsa and Jim: The syntactic sugar in this case seems VERY minimal. It's the difference between CallMyMethod(1,2,3) and CallMyMethod(new int[]{1,2,3}). Seems very minimal, so I thought there might be something more to it.Marv
F
8

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.

Fuel answered 28/4, 2011 at 17:38 Comment(7)
Ok I like that. But I think even here, the difference is really just prettier code, right? Because you could have this instead: double least = min(new double[] {x, y, z, w}) And this would not have any performance differences or anything else. Am I correct? Any other benefits?Marv
@Richard: But the whole point of high level languages is more expressive code.Gasbag
@Jim: Yeah I get that, it just seems like the difference here is so very minimal.Marv
@Richard: That's exactly what the program does. But why should I have to write twice as much code when the compiler can transform it for me? But yes, it is syntactic sugar, and the transformation is (usually) quite simple. If there are multiple overloads of the function, however, it might not be so easy to determine whether the transformation should take place, or what the resulting array type should be.Fuel
@Ben: True. Right now I am trying to get a deeper understanding, so all this syntactic sugar makes it difficult sometimes to understand what is really happening. You have to dig and dig sometimes. So I I was trying to see if there was another benefit besides just making the code more intuitive to use and read.Marv
@Richard: There's not much deeper understanding to get here. The only complication I can see at all is when this interacts with overload resolution.Fuel
@Ben: True, I can see that now, at least for this particular syntactic sugar. But I wasn't sure so I thought I would ask! :-) Delegate declarations . . . now that is some syntactic sugar that took me a lot of work to understand!!!Marv
M
5

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.

Morissa answered 28/4, 2011 at 17:41 Comment(2)
When you create your own string functions? Is that what you are saying?Marv
Yep, like say for logging info or error messages. I might have a method signature like this: 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
E
3

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.

Everlasting answered 28/4, 2011 at 17:41 Comment(0)
G
2

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[] {',', ';', ' '});
Gasbag answered 28/4, 2011 at 17:43 Comment(0)
S
1

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));   
Stun answered 28/4, 2011 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.