How to implement a custom typesafe collection using generic collections?

543 Views Asked by At

I used a strongly typed collection that derived from the CollectionBase class and now I'd like to change it to inherit from a typesafe generic collection. Some advise to inherit from List<T>, some do advise to use Collection<T>. What I'd like to do is this:

1) I have a custom class and I'm creating a collection that holds only the instances of that custom class.

2) I have some properties and methods that I'd like the custom collection class to have. For example, it should have an Id property, or it should have a IsBlahBlah() method.

How should I proceed with this? When I was deriving from the CollectionBase class, I was using the InnerList property to access the elements. Should I use the Items property if I choose to use Collection<T>?

Is doing something like:

public class MyCustomCollection : Collection<MyCustomClass>
{
    public int ExtraProperty { get; set; }

    public bool IsFortyTwo(MyCustomClass) { }
}

the right way? Will it work correctly out of the box without interfering with the methods in the Collection<T>?

Extra question: When I search for "Strongly Typed Collection" on Google, it always shows up results containing the CollectionBase class. What is the difference between Strongly Typed Collections and Typesafe Collections?

1

There are 1 best solutions below

1
On

I think its need to implement like this

public class MyCustomCollection
{
    private Collection<MyCustomClass> _collection = new Collection<MyCustomClass>();
    public int ExtraProperty { get; set; }
    public bool IsFortyTwo(MyCustomClass) { }
}