In C# is there variadic Arguments (infinite arguments)?

Asked

Viewed 90 times

2

In languages such as PHP 5.6 and Python, it is possible to define "infinite arguments", (in PHP it is called variadic args) in a function/method.

For example, it is possible to 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#? It is advantageous in any case?

And if there is, as is the Omega in C#?

  • You also have http://php.net/manual/en/function.func-get-arg.php in php. So you don’t even need to force any arguments

  • I quoted that in question :p

  • OPPS did not see that it referred to this method

2 answers

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 admit any amount of a same type of argument in your method.

See, before there is this kind of argument declared with the keyword params, a method such as the string. Format would need multiple overloads (overloads) to allow varying amounts of parameters, or require you to explicitly create an array to pass by parameter.

4


Use the modifier params:

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 more parameters are always the last.

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 Way: 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();
    }

Answer: Soen

Reference: https://msdn.microsoft.com/pt-br/library/w5zay9db.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.