Payson Welch
Payson Welch

Reputation: 1428

How do I write a C# method that takes a variable number of arguments?

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

Answers (9)

Richard Schneider
Richard Schneider

Reputation: 35464

string MyConcat(params string[] values)
{
    var s = new StringBuilder();
    foreach (var v in values)
       s.Append(v);
    return s.ToString();
}

Upvotes: 2

Reed Copsey
Reed Copsey

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

George Stocker
George Stocker

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

Mark
Mark

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

gillyb
gillyb

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

Jacob
Jacob

Reputation: 78920

Use params:

void YourMethod(params string[] infiniteArgs) { }

Upvotes: 2

Joe
Joe

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

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55519

yes, you can use params for that

Upvotes: 2

David
David

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://dotnetperls.com/main

http://msdn.microsoft.com/en-us/library/cb20e19t(VS.71).aspx

Upvotes: 0

Related Questions