Are strongly typed ArrayLists the best 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 ArrayList :

 using System.Collections; public class Emails: ArrayList { public new Email this[int i] { get { return (Email)base[i]; } set { base[i] = value; } } } 

I understand that this is probably not the right way to inherit from a collection. If I want to inherit from a strongly typed collection in C #, how do I do this, and in which class should I inherit?

+4
source share
7 answers

What you want is generic, like List<T> .

 public class Emails : List<Email> { } 

This has all the ArrayList methods, and then some, and you get type safety without having to do extra work.

Note, however, that inheriting from List<T> can sometimes cause more problems than it's worth. It is best to implement ICollection<T> or IEnumerable<T> and use List<T> to implement the interface.

+15
source

Forget both ArrayList and List. The "right" thing should be to get from the collection and call your class what ends in the collection.

 public sealed class EmailCollection : Collection<Email> { } 
+9
source

If you are not stuck with .Net 1.1, you really should forget about ArrayList and use a generic List<T> instead. You get strong typing and better download options.

+5
source

In general, new should avoid declaring a member, if at all possible.

With C # 2, although you can use generics. List<email> list = new List<email>();

+3
source

Not really, for what generics.

+2
source

Generics seem much more suitable. For instance,

 List<email> 

in this case. Why reinvent the wheel and make it worse?

+1
source

If you are using .net 2.0 or + i, you will have a common collection

0
source

All Articles