I have this code and I want to keep it elegant.
I got stuck at this inheriting issue and I would have to mess up the code if I do.
Help me keep it elegant. I don't mind making changes anywhere up and down the hierarchy; feel free to change the core.
I have these abstract classes (I omitted unrelated implementation to keep the question content short).
public abstract class Entity : IComparable
{
protected int _ID;
public abstract int ID { get; }
}
public abstract class SortedEntities<T> : IEnumerable<T> where T : Entity
{
Dictionary<int,T> _Entities;
}
And, obviously, an example of inheritance is as follows:
public class Contact : Entity { }
public class Contacts : SortedEntities<Contact> { }
And I also have more than just Contact
and Contacts
that inherit from Entity
and SortedEntities
that all act in the same manner.
At some point in my app, I want to select entities based on and ID list.
A sample code of what I want is:
Contacts LoadedContacts = new Contacts(); // load and fill somewhere else
// !!!NOT IMPLEMENTED YET!!!
Contacts SelectedContacts = LoadedContacts.GetFromIDList("1,4,7");
Where it returns a new Contacts
object filled with those Contact
objects of the ID's provided.
So, to allow that code for all classes inheriting from SortedEntities
, I thought of adding this imaginative code to the abstract:
public abstract class SortedEntities<T> : IEnumerable<T> where T : Entity
{
// !!!NOT REAL CODE YET!!!
public abstract this<T> GetFromIDList(string IDCSV)
{
List<string> idlist = IDCSV.Split(',').ToList<string>();
return this.Where(entity => idlist.Contains(entity.ID.ToString()));
}
}
But obviously the this<T>
is not allowed.
What I'm trying to tell the compiler is to make the return type of this method that of the inheriting class down the hierarchy.
That way, if someone calls LoadedContacts.GetFromIDList("1,4,7")
it will return Contacts
without having to cast it from SortedEntities<T>
if I make it the return type, which would also require me to override the method in each inheriting class to hide the abstract method.
Am I forgetting something I already know?
Or is this completely not possible and I have to override and hide the method down the hierarchy for all inheriting classes?