If I have an abstract class, is there any way I can return an enumerator of the derived class’s type? Or would I have to use generics in the base class, or a generic method? Here’s a really dumbed down example of what I’m trying to do –
public abstract class Person {
public IEnumerable<MyType> Search() {
DbDataReader reader = Database.Instance.ExecuteReader(sql);
while(reader.Read()) {
MyType row = new MyType();
row.Load(reader);
yeild return row;
}
}
private Load(DbDataReader reader) {
//load instance from reader row
}
//declare properties that can be searched, such as Location
}
public class Programmer : Person {
//declare properties that can be searched, such as Language
}
Then somewhere else I’d like to be able to call
Programmer programmer = new Programmer();
programmer.Location = "My city";
programmer.Language = "C#";
foreach(Programmer programmer in programmer.Search())
{
//display list of c# programmers in my city
}
I know I can do this with a generic method, like Search<T>(), but I’d like to be able to call the search function from a class that does not know exactly type the Person is (for example, a base class for an AJAX handler)
If this cannot be done, can anyone give me an example or reason why not? Or would it just be too hard to implement into the compiler?
If you search an approach with this “pretty” usage I propose an ExtensionMethod. With an Ext you don’t have to define the effective type of the Entity twice.
programmer.Search<Programmer>()=>programmer.Search()