Using Inheritance with Generic Collection

This is just a random tip about Generic Collections. Sometimes it’s common for me to create a class which can be used in a collection. In most cases I use a generic collection of this type as a data source and such things and instead of typing everywhere List<T> and replacing T with the type I just created; I create a new class which extends from this a generic collection of this type. Just a sample:
public class Subscriber {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string IssueId { get; set; }
    public string FullName {
        get { return string.Format("{0} {1}", this.FirstName, this.LastName); }
    }
}
Now, every time I need to instantiate a collection of Subscriber I will have to type something like this: 
List<Subscriber> list = new List<Subscriber>();
The idea here is simple. We can write a code as simple as this: 
public class Subscribers : List<Subscriber> { }
And now I can use the following code to create an instance of our collection of Subscriber: 
Subscribers list = new Subscribers();
In the end of the day, it’s just the same thing, but the advantage this is that with inheritance and polymorphism you can add other methods to your collection to handle the needs of your custom type.
Of course there are other ways of to do this, however I just wanted to comment about this one, which is the one I use in most "quick" cases.
Published Wednesday, January 28, 2009 8:23 PM by tsantos
Filed under: ,

Comments

# Using Inheritance with Generic Collection - Thiago's Blog

Thursday, January 29, 2009 10:01 AM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# re: Using Inheritance with Generic Collection

Thursday, January 29, 2009 10:21 AM by Jeff

I used to do this back in the day with ArrayList, but is it really necessary now? Especially with LINQ, it just doesn't seem like there's a lot of benefit outside of the fringe cases where you want to encapsulate domain-specific logic against that specific type.

# re: Using Inheritance with Generic Collection

Thursday, January 29, 2009 10:55 AM by tsantos

Hey there Jeff. Well, you see, it's not really necessary now, and it never was. It's just a way to keep things short for specific cases. And keep in mind that not everybody is using LINQ even tho it's out for a while now.

Leave a Comment

(required) 
(required) 
(optional)
(required)