Reputation: 1428
Is it possible to send a variable number of arguments to a method?
For instance if I want to write a method that would concatenate many string[]
objects into one string, but I wanted it to be able to accept arguments without knowing how many I would want to pass in, how would I do this?
Upvotes: 14
Views: 5685
Reputation: 35464
string MyConcat(params string[] values)
{
var s = new StringBuilder();
foreach (var v in values)
s.Append(v);
return s.ToString();
}
Upvotes: 2
Reputation: 564861
You would do this as:
string ConcatString(params string[] arguments)
{
// Do work here
}
This can be called as:
string result = ConcatString("Foo", "Bar", "Baz");
For details, see params (C# Reference).
FYI - There is already a String.Concat(params object[] args)
- it will concatenate any set of objects by calling ToString() on each. So for this specific example, this is probably not really that useful.
Upvotes: 21
Reputation: 57907
Use the params
keyword to do that:
public static string ConvertToOneString(params string[] list)
{
string result = String.Empty;
for ( int i = 0 ; i < list.Length ; i++ )
{
result += list[i];
}
return result;
}
Usage:
string s = "hello"
string a = "world"
string result = ConvertToOneString(s, a);
Upvotes: 4
Reputation: 11750
You can easily create a method that takes an arbitrary number of arguments (including zero), using the params
keyword:
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
Console.Write(list[i] + " ");
}
You can even pass an array to this method instead of a list of parameters, and the method will work exactly the same.
Upvotes: 4
Reputation: 8910
very easy to do so using params keyword
void ConcatString(params String[] strArray)
{
foreach (String s in strArray)
{
// do whatever you want with all the arguments here...
}
}
Upvotes: 3
Reputation: 47729
You don't mean infinite (the answer to that question is no) but you do mean 'variable'. Here is your answer (yes): http://blogs.msdn.com/b/csharpfaq/archive/2004/08/05/209384.aspx
Upvotes: 1
Reputation: 73594
In practice, infinite - no (there is a finite amount of memory available, for example).
Unknown at design-time, yes.
The classic example of this is how it's handled on a Console application.
http://msdn.microsoft.com/en-us/library/cb20e19t(VS.71).aspx
Upvotes: 0