What is a real example of when to use parameters as an argument to a method?

As I understand it, params is just syntactic sugar, which "under the hood" just gives you an array of the type you specify.

First, when do you use this?

Secondly, why are you using it instead of simply declaring an array argument?

+4
source share
5 answers

Math.Min takes exactly two arguments. This is a stupid restriction. Many other languages ​​allow you to write:

 double x, y, z, w; double least = min(x, y, z, w); 

If you want to write a min function that can be used as such, you should use params .

+7
source

An obvious example can be found in a method of type String.Format() . This statement using parameters is easy to follow:

 string.Format("Your name is {0}, {1}", lastName, firstName); 

But without parameters, this is a little more complicated:

 string.Format("Your name is {0}, {1}", new string[] { lastName, firstName }); 

I use params alot for string functions like these. I use it only to improve code readability.

+5
source

One of the ways I've used is to pass sql queries to my wrapper class. I will have several sql with a variable number of parameters. That way, I can just list all the parameters that I send with the request, and not create an array first.

  SQLWrapper.Query(" some sql with parameters", new SqlParameter("@param1", val1), new SqlParameter("@param1", val1), new SqlParameter("@param1", val1)); 

Much better than an alternative:

SQLWr

 apper.Query(" some sql with parameters", new SqlParameter[]{new SqlParameter("@param1", val1), new SqlParameter("@param1", val1), new SqlParameter("@param1", val1)}); 

It's nice to have when you are faced with a situation where you need a variable number of arguments.

+3
source

Example of the base class library: String.Split(params char[] separator) , which allows you to write, for example:

 var segs = myString.Split(',',';',' '); 

but not

 var sets = myString.Split(new char[] {',', ';', ' '}); 
+2
source

The main inappropriate / more understandable reason why I find myself in the parameters is to execute stored procedures.

Take the case where several hundred stored procedures are stored in a database. Then you really only have two options.

1: Enter the code separately for each stored procedure, which will take months

2: create a universal executing method that will run any stored procedure and accept any numbers and types of parameters, for example.

 databaseHelper.ExecuteStoredProcedure( "myStoredProecdure", DbProviderHelper.StringParameter("@parameter_string", somestring), DbProviderHelper.BoolParameter("@parameter_string", somebool), DbProviderHelper.IntParameter("@parameter_int", someint)); 
+1
source

All Articles