views:

368

answers:

4

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() { }
}
A: 

In C# ? - http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx

markt
+1  A: 

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 }
}
Charlie Flowers
+3  A: 

You can do something like this:

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

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

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.

Anton Gogolev