When I program in C# , there are times when I need a strongly typed collection:
I often create a class that inherits from the ArrayList:
using System.Collections;
public class Emails: ArrayList
{
  public new Email this[int i]
  {
     get
     {
        return (Email)base[i];
     }
     set
     {
        base[i] = value;
     }
  }
}
I realize this is probably not the correct way to inherit from a collection. If I want to inherit from a strongly typed collection in C#, how should I do it, and what class should I choose to inherit from?
What you want is a generic, like List<T>.
public class Emails : List<Email>
{
}
This has all of the methods of ArrayList and then some, and you get type safety without having to do any extra work.
Note, however, that inheriting from List<T> can sometimes cause you more trouble than it's worth. A better idea is to implement ICollection<T> or IEnumerable<T>, and use the List<T> internally to implement the interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With