Question

I am trying to implement an interface class, that contains a list of objects. How can I make the list generic, so that the implementing class defines the type of list:

public interface IEntity
{
    Guid EntityID { get; set; }
    Guid ParentEntityID{ get; set; }
    Guid RoleId { get; set; }

    void SetFromEntity();
    void Save();
    bool Validate();
    IQueryable<T> GetAll(); // That is what I would like to do
    List<Guid> Search(string searchQuery);
}
public class Dealer : IEntity
{
   public IQueryable<Dealer> GetAll() { }
}
Was it helpful?

Solution

You can do something like this:

public interface IEntity<T>
{
    IQueryable<T> GetAll();
}

public class Dealer : IEntity<Dealer>
{
   public IQueryable<Dealer> GetAll() { }
}

OTHER TIPS

You just need to make IEntity generic itself. Then, use the type parameter in the definition of GetAll().

Here's how you'd change your code:

public interface IEntity<TListItemType>
{
     // stuff snipped

     IQueryable<TListItemType> GetAll();
}

public class Dealer : IEntity<Dealer>
{
   public IQueryable<Dealer> GetAll() { // some impl here }
}

Adding Save(), Validate(), etc. logic to your domain object (which is what a Dealer is, I guess) is not the best idea in the world as it violates SRP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top