Call for generic methods in C#

Asked

Viewed 689 times

2

I built a generic method that suits me well, but I’m having difficulty in 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 a list of the type returned T same. I’m not sure how to call this list.

2 answers

4

There is no secret, if it was difficult could have shown the code to us to 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 took the opportunity to simplify this code, it does very little. In fact so little that if 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();
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

3


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

Below I created a class called Pessoa that I use in class MinhaClasse 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 in .Netfiddle

Browser other questions tagged

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