Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a custom typesafe collection using generic collections?

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?

like image 330
hattenn Avatar asked Mar 05 '26 18:03

hattenn


1 Answers

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) { }
}
like image 115
Aram Beginyan Avatar answered Mar 07 '26 07:03

Aram Beginyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!