Calling generic methods in C #

2

I built a generic method that suits me well, but I'm having difficulty calling this method.

 public List<T> CriaLista<T>(params T[] pars)
  {
            List<T> lista = new List<T>();
            foreach (T elem in pars)
            {
                lista.Add(elem);
            }
            return lista;
  }

I need to return a list of type T same. But I'm not sure how to call this list.

    
asked by anonymous 23.06.2017 / 02:56

2 answers

3

You call the method like any other by passing the array of type T

Below I created a class called Pessoa which I use in the MinhaClasse class where I call the method you created by passing the instances of the object of type Pessoa .

public class Pessoa
{
    public string Nome { get; set; }
}

public class MinhaClasse
{
    public void CarregarPessoas()
    {
        List<Pessoa> pessoas = CriarLista(new Pessoa{Nome = "Foo1"}, new Pessoa{Nome = "Foo2"}, new Pessoa{Nome = "Foo3"});
        foreach (var item in pessoas)
        {
            Console.WriteLine(item.Nome);
        }
    }

    public List<T> CriarLista<T>(params T[] pars)
    {
        List<T> lista = new List<T>();
        foreach (T elem in pars)
        {
            lista.Add(elem);
        }

        return lista;
    }
}

See working at .NetFiddle

    
23.06.2017 / 03:27
4

There is no secret, if you were having difficulty, you could have shown the code so we could see what was wrong. Just call and pass the parameters. Unless you are in a specific situation that creates some difficulty for the compiler.

I've used it to simplify this code, it does very little. In fact so little that if it is not to use as abstraction it should not even exist.

using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main() {
        foreach (var item in CriarLista(1, 2, 3, 4, 5, 6)) WriteLine(item);
    }
    public static List<T> CriarLista<T>(params T[] pars) => pars.ToList();
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
23.06.2017 / 05:13