c# – Receive by Parameter and Manipulate a LIST of Generic Object

Question:

I need to receive a Generic Object List by parameter and manipulate it, although searching I didn't quite understand how to do it.

Example:

public class Funcionario
{
    public long Id {get; set;}
    public string Nome {get; set;}
    public DateTime DataContrato {get; set;}
}

public class Professor
{
    public long Id {get; set;}
    public string Nome {get; set;}
    public bool IsAtivo {get; set;}
}

public void Reload(List<objeto> GridListaObjeto, int qtde)
{
    foreach (var obj in GridListaObjeto)
    {
        string sId = obj.Id;
        string sNome = obj.Nome;
    }
}

Answer:

The List<T> class is implemented in a generic way. Where T the class you want to create the list of.

For example, to use a list of teachers, your method must receive a List<Professor> professores as a parameter. Would be like this:

public void Reload(List<Professor> professores, int qtde)
{
    foreach(Professor p in professores)
    {
        string sId = p.Id;
        string sNome = p.Nome;
    }
}

For Aluno would be the same thing, it would only change the type.

Now, if in your case you really receive a List<Object> , to access the Id and Nome properties, you need to ensure that the object instance of the Object type is of the Professor or Aluno types. For that you can use is . Look:

public void Reload(List<Object> objects, int qtde)
{
    if(objects[0] is Professor) 
    {
        foreach(Object obj in objects)
        {
            Professor p = (Professor) obj;
            string sId = p.Id;
            string sNome = p.Nome;
        }
    }
}

Of course there are more "elegant" implementations, but for didactic purposes, that's it hehe. Again, for Aluno 's the same thing, just change the Professor type to Aluno .

Scroll to Top