Receive by parameter a List of miscellaneous objects

Asked

Viewed 743 times

2

I have the following problem described in the comment:

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

public class Carro{
    public long Id {get; set;}
    public string Nome {get; set;}
    public bool IsUsado {get; set;}
}

// Aqui preciso receber uma lista que as vezes será de Funcionario e outras vezes de Carro;

public static MvcHtmlString(this HtmlHelper html, List<???> listaObj){
    //Aqui dentro eu preciso saber se a lista que estou recebendo no parametro é uma lista de Funcionario ou outros...
}
  • 2

    It’s hard to understand, at what point is one and the other, should there be a decision to be made, and what is that moment? please separate explanation code!

2 answers

5


You should use a generic method there to check the type inside. But the ideal would be to make a specialized method for this case (example). I could do something like this:

using System.Collections.Generic;
using static System.Console;
using System;
                    
public class Program {
    public static void Main() {
        MvcHtmlString(new List<Funcionario> { new Funcionario() });
        MvcHtmlString(new List<Carro> { new Carro() });
    }
    public static void MvcHtmlString<T>(List<T> listaObj) {
        if (typeof(T) == typeof(Funcionario)) WriteLine("É lista de Funcionários");
        elseWriteLine("Não é lista de Funcionários");
    }
}

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

public class Carro{
    public long Id {get; set;}
    public string Nome {get; set;}
    public bool IsUsado {get; set;}
}

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

The secret there, besides using a generic type, is to check which type is being used. There are two ways to check the type:

  • a runtime is applied to existing objects. The method is used GetType() available in all objects. It returns the type object Type which can be used to do a number of things, including comparisons;
  • another is used at compile time and can only be applied to types directly. The operator is used typeof (is not a method) to obtain the object Type which can be used for what you want, in case it was used for comparison. Obviously its use is preferable whenever possible.

This is the way to check if something you don’t know the type is of a certain type. Like the method is generic and the type is variable, you have to compare the identifier that represents this generic type with the type you want. The comparison should be of types, so you need to take the object that represents the type (I’m not talking about the object of the data).

So when do I use typeof(T) I’m picking up what kind of T. It can be an object with the information of how it is composed Funcionario or how another object is composed that may be being used in the method call (I suggest following the links to better understand the genericity). On the other hand I use typeof(Funcionario). I know what the type is, but I need to get what the type representation is, so the operator is required. With the two representations I can check if they are equal (in practice it only checks if it is the same reference (memory address of type, remember that I am not talking about the objects created with data of this type, I speak of the type itself).

Use the term type that can be a class, structure, enumeration, interface or delegate.

4

What you really need is to learn how to use the operator typeof and the method GetType(). With them, you can check the type of a given variable. Note that every and every class of C# has a method GetType(). Basically, you use it typeof(T), where T is some guy. And inst.GetType(), where inst is a variable of any type.

There is also the operator is, you can see more details about the differences here.

There are several ways to do this. The simplest is to ask for one object and check the type within the method.

Can also be done with Generics or with inheritance, depending on the application architecture, note that I am not saying that you should use inheritance just because you need a method like this, I am saying that it is possible to do, if there is already a "base" class among the types that the method should receive, inheritance is possibly the best way out.

I would need more details to give an answer that fits your problem better, yet it’s impossible to say for sure, because only you know how much you want to "plaster/streamline" it.

Below an example using object and checking the type within the method.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var lista1 = new List<Carro> { new Carro() };
        var lista2 = new List<Funcionario> { new Funcionario() };

        MvcHtmlString(lista1);
        MvcHtmlString(lista2);
    }


    public static void MvcHtmlString(object lista)
    {
        if(lista.GetType() == typeof(List<Carro>))
        {
            Console.WriteLine("Lista de carros");
        } 
        else if(lista.GetType() == typeof(List<Funcionario>))
        {
            Console.WriteLine("Lista de funcionários");
        }
    }
}

Browser other questions tagged

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