Your current implementation will work as long as you produce what you do:
public class TransactionDerived : ITransaction { public bool Validate(out IResponse theResponse) { theResponse = new ResponseDerived(); ((ResponseDerived)theResponse).message = "My message"; return true; } public void Execute() { IResponse myResponse; if (Validate(out myResponse)) Console.WriteLine(((ResponseDerived)myResponse).message); } }
This is dirty. You can avoid casting by using the generic interface instead:
public interface ITransaction<T> where T : IResponse { bool Validate(out T theResponse); } public class TransactionDerived : ITransaction<ResponseDerived> { public bool Validate(out ResponseDerived theResponse) { theResponse = new ResponseDerived(); theResponse.message = "My message"; return true; } public void Execute() { ResponseDerived myResponse; if (Validate(out myResponse)) Console.WriteLine(myResponse.message); } }
source share