Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 745
Payson Welch Avatar asked Feb 14 '11 17:02

Payson Welch


People also ask

What do you write C code in?

A text editor, like Notepad, to write C code. A compiler, like GCC, to translate the C code into a language that the computer will understand.

How do you write C in numbers?

First, we will write C and LXXIII in numbers, i.e. C = 100 and LXXIII = 70 + 3 = 73. Now, 100 - 73 = 27. And 27 = XXVII. Therefore, XXVII should be subtracted from C roman numerals to get LXXIII.

Is C+ the same as C?

Conclusion. In a nutshell, the main difference between C and C++ is that C is a procedural with no support for objects and classes, whereas C++ is a combination of procedural and object-oriented programming languages.


1 Answers

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.

like image 161
Reed Copsey Avatar answered Sep 21 '22 05:09

Reed Copsey