Cannot convert from generic type to interface

c#, generics

Solution

This is indeed a **variance problem. You will need another interface for your `RegisterBlock` class, maybe `IRegisterBlock`:

public class RegisterBlock<T> : IRegisterBlock
    where T : IRegister

Then you can create a list of `IRegisterBlock`:

private List<IRegisterBlock> _blocks;

I actually had a similar situation in our code-base last week, and this is exactly how I resolved it.

Problem

I'm getting an error when trying to add generic object to a List<>. Its probably related to Covariance and Contravariance but I not sure how to work around this. I've tried to restrict my generic types using where T: IRegister. I have an interface to represent a register and then two classes which represent a ByteRegister and a DoubleWordRegister. ``` public interface IRegister { string Name {get;set;} } public class ByteRegister : IRegister { ... } public class DoubleWordRegister : IRegister { ... } ``` I then have another class which represents a block of these registers all of the same type. ``` public class RegisterBlock<T> where T:IRegister { private IList<T> _registers; ... constructors, properties etc public void AddRegister(T register) { _registers.Add(register); } } ``` And finally I have a RegisterMap class which is used to define the list of register blocks and each register within the block. ``` public class RegisterMap { private List<RegisterBlock<IRegister>> _blocks; public RegisterMap() { _blocks = new List<RegisterBlock<IRegister>>(); RegisterBlock<ByteRegister> block1= new RegisterBlock<ByteRegister>("Block1", 0); block1.AddRegister(new ByteRegister("Reg1")); block1.AddRegister(new ByteRegister("Reg2")); _blocks.Add(block1); RegisterBlock<DoubleWordRegister> block2= new RegisterBlock<DoubleWordRegister>("Block2", 10); block2.AddRegister(new DoubleWordRegister("Reg3")); block2.AddRegister(new DoubleWordRegister("Reg4")); block2.AddRegister(new DoubleWordRegister("Reg5")); _blocks.Add(block2); } } ``` However I'm getting the following error: `Error 20 Argument '1': cannot convert from 'RegisterBlock<ByteRegister>' to 'RegisterBlock<IRegister>'` on the line _blocks.Add(block1) and similarly on _blocks.Add(block2);

Original source

Related problems