Using an interface as an "out" parameter in C #

How can I use an interface or abstract class as the "out" parameter in a method in another interface? Can't I use the interface as an out parameter in another interface, and then can it accept any class that implements this interface when I actually call the method?

I need a transaction interface that has a method that returns a bool and populates a "Response" object, but this response object is a different derivative for every other transaction interface implementation. Thanks in advance.

namespace csharpsandbox { class Program { static void Main(string[] args) { TransactionDerived t = new TransactionDerived(); t.Execute(); } } public interface ITransaction { bool Validate(out IResponse theResponse); } public interface IResponse { } public class ResponseDerived : IResponse { public string message { get; set; } } public class TransactionDerived : ITransaction { public bool Validate(out IResponse theResponse) { theResponse = new ResponseDerived(); theResponse.message = "My message"; return true; } public void Execute() { ResponseDerived myResponse = new ResponseDerived(); if (Validate(out myResponse)) Console.WriteLine(myResponse.message); } } } 
+4
source share
2 answers

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); } } 
+5
source

An empty interface definition is meaningless (see here ). Instead, try something like this:

 public interface ITransaction { bool Validate(out object theResponse); } 

and then draw your object accordingly.

+1
source

Source: https://habr.com/ru/post/1435765/


All Articles