I have the following very simple and (abridged) classes:
// IEntry interface
public interface IEntry {
long Id { get; set; }
string Name { get; set; }
}
// IEntry implementation
public class Contact : IEntry {
public long Id { get; set; }
public string Name { get; set; }
}
// DAO Interface
public interface IEntryDao {
List<IEntry> findUnapproved();
}
// abstract base class
public abstract class AbstractEntryDao : IEntryDao {
public virtual List<IEntry> findUnapproved() {
List<IEntry> entries = new List<IEntry>();
// ... default load logic
return entries;
}
}
// ContactDao implementation
public class ContactDao : AbstractEntryDao {
public override List<IEntry> findUnapproved() {
List<IEntry> contacts = new List<IEntry>();
// ... custom load logic for Contact
return contacts;
}
}
// sample client code
public void testFindUnapproved() {
ContactDao contactDao = new ContactDao();
List<IEntry> contacts = contactDao.findUnapproved(); // <--- this line works (but not what I want)
List<Contact> contacts = contactDao.findUnapproved(); // <--- this does not work (which makes sense)
List<Contact> contacts = contactDao.findUnapproved() as List<Contact>; // <--- this does not work
// here is how i compensate for this problem... but i do not like this
List<Contact> list = new List<Contact>();
foreach (IManageableEntry contact in contacts) {
list.Add(contact as Contact);
}
}
What I would like is a very short hand way (or possibly using generics in the Dao interface and abstract class)
List<Contact> contacts = contactDao.findUnapproved(); // <--- can I achieve this using generics in .NET 3.5?
Otherwise, what’s a clean alternative solution other than the very end of my sample client code that I believe to be a poor practice?
Just remember to add using linq namespace above the file