Reputation: 735
I have a static class DataSource
that pulls requested data from a file and returns it as a List<IInfrastructureEntity>.
In TestRepository
(below), I am taking the generic TEntity
, determining its class type and pulling the corresponding data from DataSource
Or, trying to, at least. Instead, I get the following compile-time error on each return statement. Even though anyTEntity
necessarily implements IInfrastructureEntity
.
Cannot implicitly convert type 'System.Collections.Generic.List<IInfrastructureEntity>
' to 'System.Collections.Generic.List<TEntity>
'
How do I explicitly make that conversion?
public class TestRepository<TEntity> : IRepository<TEntity> where TEntity : IInfrastructureEntity
{
public List<TEntity> GetData()
{
TEntity checkType = default(TEntity);
if (checkType is Member) return DataSource.Members;
if (checkType is MenuItem) return DataSource.MenuItems;
if (checkType is CRAWApplication) return DataSource.CRAWApplications;
if (checkType is CRAWEntitlement) return DataSource.CRAWEntitlements;
if (checkType is FOXGroup) return DataSource.FOXGroups;
throw new NotSupportedException( checkType.ToString() + " is not yet supported");
}
public List<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
{
return GetData().AsQueryable().Where(predicate);
}
}
Upvotes: 2
Views: 196
Reputation: 53958
You could fix this by imposing an explicit cast in each list your return:
if (checkType is Member) return DataSource.Members.Cast<TEntity>().ToList();
The problem is that the type of DataSource.Members
is List<IInfrastructureEntity>
, whereas the type that is expected to be returned is a List<TEntity>
. Indeed each Entity
should implement IInfrastructureEntity
as you have stated this as where TEntity : IInfrastructureEntity
. However even if a type implements this interface it doesn't mean that this type can be converted implicitly to TEntity
object. This is why you need the explicit cast.
Upvotes: 2