I have a much more complicated issue, but I’ve boiled it down to the following simple example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
IFactory<IProduct> factory = new Factory();
}
}
class Factory : IFactory<Product>
{
}
class Product : IProduct
{
}
interface IFactory<T> where T : IProduct
{
}
interface IProduct
{
}
}
All is well and dandy… except that I get this error.
Error 1 Cannot implicitly convert type Sandbox.Factory to Sandbox.IFactory<Sandbox.IProduct>. An explicit conversion exists (are you missing a cast?) c:\~~\Program.cs 12 42 Sandbox
Anyone willing to provide insight into why this is the case? I’m sure Jon Skeet or Eric Lippert could explain in a heartbeat why this is, but there has to be someone that not only understands WHY this can’t be inferred, but can explain how best to solve this situation.
Follow up question here
It is because
Factoryis anIFactory< Product>and what you are assigning it to is aIFactory< IProduct>, and sinceIFactoryis not covariant, you cannot cast a generic of subtype to a generic of supertype.Try making
IFactory< out T>, which should make the following assignment work.EDIT:
@Firoso, in your factory interface you are trying to create a list, in which you can write to. If your interface is covariant you can not write to anything, because of the following:
You should ignore covariance in your case and just create assign to an
IFactory<Product>instead or change factory to inheritIFactory<IProduct>instead, I recommend the latter but it is up to you