In C # is there variadic arguments? [duplicate]

2

In languages such as PHP 5.6 and Python , you can define "infinite arguments" (in PHP it is called vadicadic args ) in a function / method

For example, you can define a function like this in PHP 5.6:

 function variadic($name, ...$args) {

      echo $name;

      foreach ($args as $key => $value) {
          echo $value;
      }
 }

 variadic('name', 1, 2, 3, 4, 5, 6);

That is, from the second argument on, we can pass "infinite" arguments to the function.

Is there any way to do this in C #? Is it advantageous in some case?

And if so, what is the C # naming?

    
asked by anonymous 14.06.2016 / 18:18

2 answers

4

Use the params switch:

public class MyClass
{
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

Note: This modifier has to be used alone, or if you have more parameters always be the last one.

Example:

Correct form:

public class MyClass
{
    public static void UseParams(string c, string d, params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

Wrong Form: Causes errors and does not compile

public class MyClass
{
    public static void UseParams(params int[] list, string d)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }

Response: SOEn

Reference link

    
14.06.2016 / 18:21
4

Yes, there is. Example:

string.Format(string format, params object[] args);

Consumption:

string.Format("Meu nome é {0}, eu tenho {1} anos", "Caffé", 36);

The difference is that in C # the typing is static.

It is advantageous in cases when you want to allow any amount of the same type of argument in your method.

See, before there is this type of argument declared with the params keyword, a method like string.Format would need several overloads to allow for varying number of parameters, or would require you to explicitly create an array to pass by parameter.

    
14.06.2016 / 18:21