Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Strongly typed ArrayLists the better choice in C#?

Tags:

c#

.net

arraylist

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?

like image 873
Tom Avatar asked Nov 28 '22 03:11

Tom


1 Answers

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.

like image 80
JSBձոգչ Avatar answered Dec 15 '22 00:12

JSBձոգչ