I’m pretty sure there is a simple answer to this that revolves around co-variance but I’m struggling to see it!
I have a class like so:
internal sealed class GenericCallbackClass<T> : SomeBaseClass
where T : ICallbackMessageBase
{
public GenericCallbackClass(string activeId, T message)
: base(activeId)
{
Message = message;
}
public T Message { get; private set; }
}
I then create an instance of a class that implements ICallbackMessageBase called Foo and instantiate a new GenericCallbackClass passing this in as the argument for T
e.g. var myCallback = new GenericCallback<Foo>("SomeID", new Foo())
I now want to cast this to a more generic instance of the GenericCallbackClass because I will have many instances of this with Foo, Bar etc but all implement ICallbackMessageBase.
So I want to do something like var callback = myCallback as GenericCallbackClass<ICallbackMessageBase>
It appears I can’t do this cast… Any ideas how I should get around this?
Why do you need Generic
<T>‘s at all in this situation. Is there some other code in your GenericCallback class that leverages<T>. Otherwise you can just rely on the interface implementation of each object and ensure that the Interface defines any common properties or operations you may need in your Callback class.