Number of variable parameters in C #

2

I know you can do this. But I can not seem to find it.

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

So I can simply call it like this:

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

instead of calling by creating an array (polluted):

UIMostra(new string[]{"Localização", "Informações Gerais", "Acessos"})
    
asked by anonymous 07.02.2014 / 18:58

2 answers

6

Use the keyword params , which allows you to indicate that an array argument will receive a parameter list without explicitly passing an array.

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

The argument that receives the keyword params should be the last one, and should be declared along 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 like this:

MetodoComListaDeInteiros(1, 2, 5, 10);

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

MetodoComListaDeInteiros(new int[] { 1, 2, 5, 10 });
    
07.02.2014 / 19:01
2

It is possible to improve the first example described by Miguel Angelo. Instead of using object type variable, you can achieve the same result, but with better use of resources using Generics . It would look like this:

Method declaration

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

Usage:

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);
    
11.02.2014 / 01:39