After passing a class by interface reference, how to recover your Type?

Asked

Viewed 30 times

2

If I receive a class by interface reference, is there any way to recover the original type that implemented it?

This way I could spend it on an overload of methods for each specific type. Or this is not appropriate/possible?

1 answer

2


Yes, it’s possible and it’s very quiet.

You can define whether an object is of a certain type using the operators is and as.

If you are using new versions of C# (7 or higher), you can use Pattern matching to solve this problem.

For example:

void Main()
{
    Console.WriteLine(Metodo(new Classe1()));
    Console.WriteLine(Metodo(new Classe2()));
}

string Metodo(Interface parametro)
{
    // fazer algo aqui
    
    var retorno = parametro switch
    {
        Classe1 c => MetodoClasse1(c),
        Classe2 c => MetodoClasse2(c),
        _ => throw new Exception("Tipo não tratado")
    };
    
    return retorno;
}

string MetodoClasse1(Classe1 parametro) => parametro.PropriedadeX;
string MetodoClasse2(Classe2 parametro) => parametro.PropriedadeY;

interface Interface { }

class Classe1 : Interface 
{ 
    public string PropriedadeX => "Classe 1";
}

class Classe2 : Interface
{
    public string PropriedadeY => "Classe 2";
}
  • I need to give an exit, but already edit with more details about operators is and as.

  • Anyway, thank you very much for the reply!

Browser other questions tagged

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