public interface IPopProtocol : IProtocol
{
void SomeUniqueMethod();
}
public interface IProtocol
{
}
public interface IProtocolManager
{
void SendMessage(IProtocol protocol, string message);
}
public interface IProtocolSender<out T> where T : IProtocol
{
T Protocol
{
get;
}
}
public class PopProtocol : IPopProtocol
{
public void SomeUniqueMethod()
{
Console.WriteLine($"Hi, I'm {nameof(PopProtocol)}");
}
}
void Main()
{
var sender = new ProtocolSender<IPopProtocol>(new PopProtocol());
var manager = new ProtocolManager();
manager.SendMessage(sender.Protocol, "Testing");
sender.Protocol.SomeUniqueMethod();
}
public class ProtocolManager : IProtocolManager
{
public void SendMessage(IProtocol protocol, string message)
{
}
}
public class ProtocolSender<T> : IProtocolSender<T> where T : IProtocol
{
private T _protocol;
public T Protocol => _protocol;
public ProtocolSender(T protocol)
{
_protocol = protocol;
}
}
Not sure what the fuss is: you can use SendMessage as usual, and also have access to SomeUniqueMethod.EDIT:
Also please note that the signature for the generic IProtocolSender uses the out keyword, making it covariant. This will allow you to cast IProtocolSender<IPopProtocol> to IProtocolSender<IProtocol> if you need to, or to pass an IProtocolSender<IPopProtocol> object to a method that expects an IProtocolSender<IProtocol>.