In my base-class (Entity
) I have implemented a method (GetEntity
) defined by my interface (IEntity
). That method works on a generic type (TEntity
) constrained to the interface type. In said method, I would like to take the generic type and cast it as a base-class type to access a member (ParentKeyFields
) defined in the base-class. Here is the code:
public interface IEntity
{
TEntity GetEntity<TEntity>(string identifier) where TEntity : IEntity;
}
public class Entity : IEntity
{
private readonly IDataProvider DataProvider;
private readonly IUserContext UserContext;
public List<string> ParentKeyFields { get; set; }
public Entity(IDataProvider dataProvider, IUserContext userContext)
{
// ...
ParentKeyFields = new List<string>();
}
public TEntity GetEntity<TEntity>(string identifier) where TEntity : IEntity
{
// Approach #1:
TEntity result = default(TEntity);
List<string> test = ((Entity)result).ParentKeyFields;
// This gives me an error saying: "Cannot conver type 'TEntity' to 'Entity'".
// Approach #2:
Entity result = (TEntity) new Entity(DataProvider, UserContext);
// This gives me an error saying: "Cannot convert type 'Entity' to 'TEntity'.
List<string> test = result.ParentKeyFields;
return result;
// This gives me an error saying: "Cannot implictly convert type 'Entity' to 'TEntity'".
}
}
I am unable to access the member (ParentKeyFields
). I've tried casting on object creation and when accessing the member. Neither approach will compile.
I want to access the different values that may be defined in that member for different derived types:
class Company : Entity
{
public Company(IDataProvider dataProvider, IUserContext userContext) : base(dataProvider, userContext)
{
}
}
public class Employee : Entity
{
public Employee(IDataProvider dataProvider, IUserContext userContext) : base(dataProvider, userContext)
{
ParentKeyFields.Add("co");
}
}
public class EIns : Entity
{
public EIns(IDataProvider dataProvider, IUserContext userContext) : base(dataProvider, userContext)
{
ParentKeyFields.Add("co");
ParentKeyFields.Add("id");
}
}
class Program
{
static void Main(string[] args)
{
Entity test = system.GetEntity<Employee>("foobar");
}
}
I am new to interfaces and how they are implemented, so my naivety may be steering me in the wrong direction. How may I reconstruct my code to make this work?