I need to write a function that will take a variable number of arguments. I read a little about params[], but I don't think that will work in my case. My function needs to take a variable number of ints and then a corresponding bool value for each of them. I have to iterate through each of these combinations and input them into a database. Just looking for someone to point me in the right direction. Thanks.
Yes you can pass variable no. of arguments to a function. You can use apply to achieve this.
There can be only one variable argument in a method. Variable argument (Varargs) must be the last argument.
Answer 1: When it comes to passing arguments to function, the maximum number of arguments that is possible to pass is 253 for a single function of the C++ programming language.
Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.
I would recommend building a struct and then passing those in as params. In my example, your struct represents a score of some kind:
public struct RaceScore
{
public bool FinishedRace;
public int Points;
}
Your method signature would then be:
public void SaveScores(params RaceScore[] scores)
Here's an example of calling SaveScores:
RaceScore score = new RaceScore() { FinishedRace = true, Points = 20 };
RaceScore score2 = new RaceScore() { FinishedRace = false, Points = 15 };
SaveScores(score, score2);
You can do this with params, but the params needs to be some class or struct that holds your int + your bool. KeyValuePair<TKey,TValue>
in the base class libraries would work, if you don't want to write your own class or struct.
If you're going to iterate through them, though, I'd recommend using IEnumerable<T>
instead, though, as it's much simpler to use.
For example:
public void SaveValues(IEnumerable<KeyValuePair<int,bool>> values)
{
foreach(var pair in values)
{
int intVal = pair.Key;
bool boolVal = pair.Value;
// Do something here...
}
}
The same thing would work with params, ie:
public void SaveValues(params KeyValuePair<int,bool>[] values)
This, though, forces you to make an array. Using IEnumerable<T>
will work with an array, but will also work with lists of values, or LINQ query results, etc. This makes generating calling this function easier in many cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With