There are times when having your own collection of objects can come in handy in an application. Say for instance you want to create an list object that you can add or remove items from and then do something with the collection as a whole. Sure you could pass around the Generic List object of your given object type and create a method that does what you want and accepts the generic list, but that seemed rather disconnected to me.
I had the need to create a collection of a custom class in an application I was writing and I needed the ability to call several methods against that collection. I could have created a class that was instantiated and then took in the collection in the method calls or had the collection as a property of the class itself, but that still didn’t seem fluid enough. I only wanted one object that I could add objects to and also call custom methods against, because to me that seemed like the most streamlined way to do it.
So that is when I started looking into inheriting from the IList interface. Creating a custom collection class object that I could then add custom methods to that would interact with the collection itself rather than a property of the class or an entirely different object passed in through a parameter. It took me awhile to get the correct usage of the interface in place and find the simplest solution to implementing it but eventually I came up with adding a private variable that is the same type as the collection that the class implements. I simply call my the methods on my private list when the methods are called on my custom class.
This allowed me to have all the functionality of a collection in a single class and still write my own methods to implement the functionality and interaction I wanted to have with that collection. I have written a basic example of the concept using a List object of type string. It should be noted that if you want to entirely replicate the functionality of the Generic List object type you will need to inherit from multiple interfaces. The interfaces that the Generic List object type itself inherits from are: IList
In my example I only inherit from IList for simplicity, you can and should inherit from all the interfaces if you wish to completely replicate the functionality of a Generic list in your custom collection. In my example you can also see that I have only one simple method that can be called on the collection and it just simply concatenates my basic string collection together into a simple string.

Recent Comments