How to initialize an interface that has type aguments of the type of another Interface

c#

Solution

Pretty sure you're moving into the realm of covarience here with the Generic change;

try this:

public interface IModel{}
public interface IGenericMapper< out T> where T : IModel{}
public class ActualModel : IModel{}
public class ActualMapper : IGenericMapper<ActualModel>   {}

and then:

IGenericMapper<IModel> blah = new ActualMapper();

with out the 'out T' the best you can do is:

IGenericMapper<ActualModel> blah = new ActualMapper();

This is a rabbit hole, so be careful especially if you ever try to mix the two :)

http://msdn.microsoft.com/en-us/library/ee207183.aspx

[Edit]

If you want to be able to downcast the generic `T`, then it has to be `out` and you cannot use it as an input. You can, however, move some of it to real time in your implementation; i.e. to a check to see if you can cast it to a model type.

interface IGenericMapper<out TModel, in TKeyOrIdent> 

TModel GetModel(TKeyOrIdent bBusinessObject);
void SetModel(object model, TKeyOrIdent target);

Problem

ive run into a problem - these is my class structure ``` public interface IModel{} public interface IGenericMapper<T> where T : IModel {...} public class ActualModel:IModel {...} public class ActualMapper: IGenericMapper<ActualModel> {...} ``` My actual code to initialse the mapper is: ``` IGenericMapper<IModel> mapper; mapper= new ActualMapper(); ``` It does not compile. I get the error Cannot implicitly convert type 'ActualMapper' to 'IGenericMapper'. An explicit conversion exists (are you missing a cast?) When I do cast it using ``` mapper= new ActualMapper() as IGenericMapper<IModel>; ``` the mapper does not get initialized properly (it comes back as NULL) What am I missing - since `ActualMapper()` implements `IGeneric` Mapper and its type impliments `IModel' why can it not initialize mapper. Is there another way to structure this so achieve what I need? Thank you so much Note the solution people have proposed gives me other compilation errors as the mapping Interface has the following members ``` T GetModel(busO bBusinessObject); busO SetBusObject(T source, busO target); ``` apparently you cant have the generic type as an input parameter when its declared at "out"

Original source