Tom
Tom

Reputation: 962

Are Strongly typed ArrayLists the better choice in C#?

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?

Upvotes: 4

Views: 4426

Answers (7)

JSBձոգչ
JSBձոգչ

Reputation: 41378

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.

Upvotes: 14

Josh
Josh

Reputation: 69262

Forget both ArrayList and List. The "right" thing to do would be to derive from Collection and call your class something that ends in Collection.

public sealed class EmailCollection : Collection<Email>
{

}

Upvotes: 9

Clay Fowler
Clay Fowler

Reputation: 2078

Generics seem much more appropriate. For example,

List<email> 

in this case. Why reinvent the wheel and perform worse?

Upvotes: 1

Hannoun Yassir
Hannoun Yassir

Reputation: 21192

If you use .net 2.0 or + i would go with a generic collection

Upvotes: 0

Yann Schwartz
Yann Schwartz

Reputation: 5994

If you're not stuck with .Net 1.1, you really should forget about ArrayList and use the generic List<T> instead. You get strong typing and better performances to boot.

Upvotes: 5

dkackman
dkackman

Reputation: 15559

In general new should be avoided for member declaration if at all possible.

As of C# 2 though you can use generics. List<email> list = new List<email>();

Upvotes: 3

Ot&#225;vio D&#233;cio
Ot&#225;vio D&#233;cio

Reputation: 74270

Not really, that's what generics are for.

Upvotes: 2

Related Questions