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");
}
}
}
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!
– novic