Creating methods with infinite parameters?

In C # you can do this:

foo = string.Format("{0} {1} {2} {3} ...", "aa", "bb", "cc" ...); 

This Format() method takes infinite parameters, being the first how the string should be formatted, and the rest as values ​​that should be placed in the string.

Today I came to a situation where I had to get a set of strings and test them, then I remembered this language functionality, but I had no idea. After several unsuccessful searches on the Internet, I realized that it would be wiser to just get an array that did not make me completely satisfied.

Q: How to create a function that takes infinite parameters? And how to use it?

+44
function c # method-overloading
Mar 12 '10 at 20:44
source share
8 answers

C params keyword.

Here is an example:

  public int SumThemAll(params int[] numbers) { return numbers.Sum(); } public void SumThemAllAndPrintInString(string s, params int[] numbers) { Console.WriteLine(string.Format(s, SumThemAll(numbers))); } public void MyFunction() { int result = SumThemAll(2, 3, 4, 42); SumThemAllAndPrintInString("The result is: {0}", 1, 2, 3); } 

The code shows various things. First of all, the argument with the params should always be the last (and there can only be one function). Alternatively, you can call a function that takes params two ways. The first path is illustrated in the first line of MyFunction , where each number is added as one argument. However, it can also be called using an array, as shown in SumThemAllAndPrintInString , which calls SumThemAll with an int[] called numbers .

+73
Mar 12 '10 at 20:45
source share
β€” -

Use the params keyword. Using:

 public void DoSomething(int someValue, params string[] values) { foreach (string value in values) Console.WriteLine(value); } 

A parameter that uses the params keyword always ends.

+19
Mar 12
source share

A few notes.

Paramas should be marked by array type, for example string [] or object [].

The parameter denoted by w / params should be the last argument to your method. For example, Foo (string input1, object []).

+6
Mar 12
source share

use params . for example

 static void Main(params string[] args) { foreach (string arg in args) { Console.WriteLine(arg); } } 
+3
Mar 12
source share

You can achieve this using the params keyword .

A small example:

 public void AddItems(params string[] items) { foreach (string item in items) { // Do Your Magic } } 
+3
Mar 12
source share
  public static void TestStrings(params string[] stringsList) { foreach (string s in stringsList){ } // your logic here } 
+3
Mar 12
source share
  public string Format(params string[] value) { // implementation } 

The params keyword is used.

+1
Mar 12
source share
 function void MyFunction(string format, params object[] parameters) { } 

Instad object [] you can use any type that you like. The params argument must always be the last in a string.

+1
Mar 12
source share



All Articles