Here is my example interface:
public interface IJob<T, R>
where T : IStep
where R : IDelivery
{
T Step { get; set; }
R Delivery { get; set; }
}
Here is my example implementation
public class ImageJob<T, R> : IJob<T, R>
where T : ImageStep
where R : ImageDelivery
{
public T Step { get; set; }
public R Delivery { get; set; }
}
Both ImageStep and ImageDelivery implement their respective interfaces (IStep, IDelivery)
Now what I’m trying to do is interface all of my repository methods. Let’s take this method for example:
public void CreateJob(IJob<IStep, IDelivery> job);
So I create a new:
var job = new ImageJob<ImageStep, ImageDelivery>
{
...
}
And then I try to pass that into the repository method:
repository.CreateJob(job);
And I get an error saying:
Unable to cast ImageJob<ImageStep, ImageDeliver> to type IJob<IStep, Idelivery>
Can someone explain to me why this is throwing an error? Am I implementing and interfacing totally wrong?
Is there an elegant to solution to what I’m trying to do?
I want to abstract out each Job with different Step and Delivery methods, etc. Is this possible some other way? Or am I missing something entirely?
I think could use Covariance. This enables you to cast a specific Generic type to one of its Generic interfaces or base classes like:
Class and interface decleration:
The “out” keyword in the Generic decleration enables the cast.
Here is a nice page on the MSDN which may help you further
In your case it would be (if you don’t net the setters in the interface
This should work with your implemented class