khaloud1980
khaloud1980

Reputation: 43

casting classe to interface

I have a problem with casting a generic class to the interface it is implementing.

My code is like this:

public interface IRepository<T> where T : EntityBase
{
    T GetByID(Int32 Id);
    Int32 Add(T entity);
    void Update(T entity);
    void Delete(Int32 Id);
    DataTable GetAll();

}

public class Benificiares : BaseRepository, IRepository<Benificiare>
{
    public  int Add(Benificiare benificiare)
    {
    }

    public DataTable GetAll()
    {
    }

    public Benificiare GetByID(int Id)
    {
    }

    public void Update(Benificiare benificiare)
    {
    }

    public void Delete(Int32 Id)
    {
    }
}

This class base controller that make common functionalties of my controllers and I want to pass it any repository

public abstract class EntitiesController
{
    public DataTable List_Items;
    public OleDbDataAdapter _Da;
    public DataSet _Ds;
    public BindingSource _Bs;
    public DataGridViewX Grid_Items;
    public IRepository<EntityBase> _repository;
    public BaseRepository base_repo;
    public abstract void InitGridItems(DataGridViewX Grid_Items);

    public EntitiesController(DataTable table, OleDbDataAdapter Da, DataSet Ds,BindingSource Bs,DataGridViewX Grid)
    {
        _Ds = Ds;
        _Bs = Bs;
        List_Items = table;
        _Da = Da;
        Grid_Items = Grid;
    }
}

and the last one

public class BenificiaresController : EntitiesController
{
    private Benificiares repository = new Benificiares();
    private Benificiare benificiare = new Benificiare();

    public BenificiaresController(DataTable List_Benificiare,OleDbDataAdapter Da,DataSet Ds ,BindingSource Bs,DataGridViewX Grid)
        :base(List_Benificiare,Da,Ds,Bs,Grid)
    {
        base._repository = (IRepository<EntityBase>)repository;
    }

this line generate exception

base._repository = (IRepository<EntityBase>)repository;

Can not cast type of ....... class Benificiares to Interface IRepository

Upvotes: 0

Views: 42

Answers (1)

DavidG
DavidG

Reputation: 118957

You can't simply assign Foo<Derived> to IFoo<Base> because the interface isn't covariant/contravariant. However, you can make your base controller generic too. For example:

public abstract class EntitiesController<TEntity> where TEntity : EntityBase
{
    public IRepository<TEntity> _repository;

    //snip
}

And your controller would change to something like this, also removing the need to cast:

public class BenificiaresController : EntitiesController<Benificiare>
{
    public BenificiaresController(.....) : base(....)
    {
        base._repository = repository;
    }
}

Upvotes: 2

Related Questions