Is it possible to convert Class<T> Where T : IMySampleInterface
to Class<IMySampleInterface>
Example:
public abstract class AbstractCommunication: ICommunication
{
private ICommunicationCallback<ICommunication> callback = null;
public void registerCommunicationCallback<T>(ICommunicationCallback<T> callback) where T : ICommunication
{
this.callback = (ICommunicationCallback<ICommunication>)callback; //<--DOESNT WORK
}
}
In my Example the following exception occurs: System.InvalidCastException
Edit:
public interface ICommunicationCallback<T> where T : ICommunication
{
void onCommunicationCallback(T sender, String data);
}
why do i use this way: If I have a base class that should implement for example two Callbacks than i could simply use the following:
public class TestClass : ICommunicationCallback<TestClass1>, ICommunicationCallback<TestClass2>
TestClass1:
public class TestClass1: AbstractCommunication
{
}
TestClass2:
public class TestClass2: AbstractCommunication
{
}
Edit: "if T is always an ICommunication, then why keep it generic? – Davin Tryon 20 mins ago" Im locking at this point
Okay Without the generics i got the same error but different System.InvalidCastException
:
(That is why i used generics in the first place - i remember now)
public class DocumentTest : ICommunicationCallback<GetDocumentData>
{
public void callAsync()
{
CommunicationFactory comFactory = new CommunicationFactory(communicationServiceClient);
GetDocumentData getDocumentData = (GetDocumentData)comFactory.createCommunicationObject(CommunicationFactory.ENTITY_TYPE.GET_DOCUMENT_DATA,(ICommunicationCallback<ICommunication> ) this);
}
}
public interface ICommunicationCallback<ICommunication>
{
void onCommunicationCallback(ICommunication sender, String data);
}
I Think using generics is the only solution in my case - see: "This feature works only for generic interfaces and delegates. If you implement a variant generic interface, the implementing class is still invariant. Classes and structs do not support variance in C# 4.0. So the following doesn’t compile: // List implements the covariant interface // IEnumerable. But classes are invariant. List list = new List(); // Compiler error here." (http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx)