C# List Collections – Is Inheriting List to Implement Collections a Bad Idea?

c++collectionslist

I once read an article by Imaar Spaanjars on how to build 3 tier applications. (http://imar.spaanjaars.com/416/building-layered-web-applications-with-microsoft-aspnet-20-part-1) which has formed the basis of my coding for a while now.

Thus I implement collections as he has done, by inheriting a List<T>. So if I have a class named Employee,to implement a collection I will also have a class Employees as below.

class Employee
{
   int EmpID {get;set;}
   string EmpName {get;set;}  

}

class Employees : List<Employee>
{
   public Employees(){}
}

I never really questioned this as it did the work for me. But now that I started trying out a few things I am not sure if this is the correct approach.

e.g. if I want to get a subset from Employees, such as

 Employees newEmployees = (Employees) AllEmployees.FindAll(emp => emp.JoiningDate > DateTime.Now);

This throws a System.InvalidCastException . However, if I use the following then there is no Issue.

List<Employee> newEmployees = AllEmployees.FindAll(emp => emp.JoiningDate > DateTime.Now);

So how do I implement Employees so that I dont have to explicitly use List<Employee> in my DAL or BLL? Or maybe how do I get rid of the InvalidCastexception?

Best Answer

I wouldn't inherit from List<T> - it introduces issues like these, and doesn't really help (since there are no virtual methods to override). I would either use List<T> (or the more abstract IList<T>), or to introduce polymorphism Collection<T> has virtual methods.

As a note; re things like FindAll, you may also find the LINQ options (like .Where()) useful counterparts; most notably, they will work for any IList<T> (or IEnumerable<T>), not just List<T> and subclasses.

Related Question