mahboub_mo
mahboub_mo

Reputation: 3038

How to copy an object of a generic class to another object with inherited type?

Because i don't know how to explain my problem clearly,i give an example! I have these Interfaces and classes:

public interface IParam
{
   ....
}

public class Param1:IParam
{
   ....
}

public class Param2:IParam
{
   ....
}

public interface IParamDbService<TEntity> where TEntity : IParam
{
    IQueryable<TEntity> GetAll();
}

public class Param1DbService : IParamDbService<Param1> 
{
   public IQueryable<Param1> GetAll()
   {
      ...
   }
}  

public class Param2DbService : IParamDbService<Param2> 
{
   public IQueryable<Param2> GetAll()
   {
      ...
   }
}  

And in some cases i need to do this:

 IParamDbService<Param> paramDbService;
 IParamDbService<Param1> param1DbService;
 IParamDbService<Param2> param2DbService;

 paramDbService=param1DbService; or  paramDbService=param2DbService;

I use paramDbService in my code so sometimes i need to copy param1DbService into it and the othertime param2DbService.but they have different type so i can't do that.Any ideas?

Upvotes: 2

Views: 130

Answers (1)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

Make it covariant (note the out TEntity):

public interface IParamDbService<out TEntity> where TEntity : IParam
{
    IQueryable<TEntity> GetAll();
}

IParamDbService<IParam> paramDbService;
IParamDbService<Param1> param1DbService;

paramDbService=param1DbService

If you add other methods to the DbService, which get TEntity as argument, it is not covariant anymore. You need to split the interface into a DbReader<out TEntity> with only the reading part and and DbService<TEntity> with everything else.

Alternatively, you could make the writing members based on IParam to make them covariant as well.

Upvotes: 2

Related Questions