Number of variable parameters in C#

Asked

Viewed 256 times

2

I know you can do this. But I can’t find how.

How do I make a function accept a variable number of parameters of the same type, similar as an array?

So I can just call it that:

UIMostra("Localização", "Informações Gerais", "Acessos")

instead of calling creating an array (polluted):

UIMostra(new string[]{"Localização", "Informações Gerais", "Acessos"})

2 answers

6


Use the keyword params, which allows you to indicate that an array argument will receive a list of parameters without having to pass an array explicitly.

public void MeuMetodo(params object[] meusParametros)
{
    // usar o array de parametros
}

The argument that receives the keyword params must be the last, and must be declared together with an array type.

To pass a list of integers, for example:

public void MetodoComListaDeInteiros(params int[] arrayInteiros)
{
    // faça algo com os inteiros... e.g. iterar eles num laço for, e mostrar na tela
    foreach (var eachNum in arrayInteiros)
        Console.WriteLine(eachNum);
}

and then call it that:

MetodoComListaDeInteiros(1, 2, 5, 10);

Every method that accepts a list, also accepts an array, so the same method above can also be called:

MetodoComListaDeInteiros(new int[] { 1, 2, 5, 10 });

2

It is possible to improve a little the first example described by Miguel Angelo. Instead of using variable of type Object, it is possible to obtain the same result, but with better use of resources with the use of Generics. It would look like this:

Method declaration

public void MeuMetodo<T>(params T[] meusParametros)
{
    foreach(T parametro in meusParametros)
        //restante do código
}

Utilizing:

public class Cliente
{
    public Cliente(int id, String nome)
    {
        this.Id = id;
        this.Nome = nome;
    }
    public int Id { get; set; }
    public String Nome { get; set; }
}

Cliente cli1 = new Cliente(1, "João");
Cliente cli2 = new Cliente(2, "Maria");
Cliente cli3 = new Cliente(3, "José");

MeuMetodo<Cliente>(cli1, cli2, cli3);

Browser other questions tagged

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