Return derived type in derived function

671 views Asked by At

I have a search form that executes queries returning lists of objects that are sub-classes of a Contact class.

When the lists are used in gridviews, properties that only exist in sub-classes (such as HireDate) are not displayed because the list contains objects of the base class (Contact).

Is there a way to make GetContacts in the sub-class return a list of Employee instead of a list of Contact ? Or a way to "cast" the list of Contact into a list of Employee ?

Thanks in advance !

public abstract class Contact  
{  
    public string Name { get; set; }  
}

public class Employee : Contact  
{
    public DateTime HireDate { get; set; }
}

public abstract class ContactManager  
{  
     public abstract List<Contact> GetContacts(string searchValue);  
}  

public class EmployeeManager : ContactManager  
{  
     public abstract List<Contact> GetContacts(string searchValue);  
} 
2

There are 2 answers

8
Rich O'Kelly On BEST ANSWER

Yes, generics can help here:

public abstract class ContactManager<T> where T : Contact
{  
  public abstract List<T> GetContacts(string searchValue);  
}

public class EmployeeManager : ContactManager<Employee>
{  
  public abstract List<Employee> GetContacts(string searchValue);  
}

Alternatively, you can use the LINQ OfType method to get all contacts of a desired type from your collection:

IEnumerable<Employee> employees = contactManager.GetContacts("someSearchValue").OfType<Employee>();
0
Grant Thomas On

You could use generics, something like this:

public abstract class ContactManager<TContactType> 
    where TContactType : Contact 
{
    public abstract List<TContactType> GetContacts(string searchValue);  
}

public abstract class EmployeeManager : ContactManager<Employee> 
{
    ...
}

This allows you to constrain ContactManager to work with specific a specific base type (i.e Contact) and further use the specific type (of Contact) to drill down with strong typing, for instance, with Employee.