In a general way Andrew’s answer works, after all if you’re sure you passed a Funcionario
for the method then knows what to make a cast of the returned object to Funcionario
will work. Without that certainty this would be a danger.
A more "modern" way of doing this is what Gabriel Katakura’s response says. Making a generic method you already guarantee that the type returned will be the type you passed to the method, so you do not need to make a cast and is safer.
public T Teste<T>(T pessoa) where T : Pessoa {
//faz o que deseja aqui
return pessoa;
}
Calling for:
var func = new Funcionario();
func = Teste(func); //ele infere, se não fosse possível chamaria Teste<Funcionario>(func)
I put in the Github for future reference.
Note that in this case the compiler will generate a specialized method that will receive an object of some type and return an object of the same type. This is defined by the parameter T
which is a super variable of type. I said it receives any object, but it’s not like that. It has a restriction saying that the T
must be any kind, as long as he’s a Pessoa
, therefore derivative types are valid, others are not. More details are in the question linked above.
When you compile that code it’s like you’ve written:
public Funcionario Teste(Funcionario pessoa) {
//faz o que deseja aqui
return pessoa;
}
But you didn’t have to write, that’s the beauty of genericity. The compiler adapts your method to every type you use. It will be defined by the use of the method. This is called client site, or Consumer site.
Obviously you still can’t do anything specific to an object Funcionario
or Cliente
, can only do things available in Pessoa
. If you want to do something specific than just one Funcionario
can then must do something with Funcionario
even.
public Pessoa Teste<Pessoa>(Pessoa pessoa) { }
so at least did not give compilation error, but why is the big question!– Jedaias Rodrigues
I don’t understand what the point is to decide what’s best for you.
– Maniero
ClienteId
andFuncionarioId
are not necessary. You can remove them from the Models derivatives.– Leonel Sanches da Silva