Why isn't ArrayList marked [Obsolete]?

5k views Asked by At

After a deep thought and looking into the implementation of ArrayList, personally I really want to say It's obsolete, I have no reason to use this class after 2.0. But since it's not marked as [Obsolete], is there any usage that I didn't know, better than using a generic class? If yes, please give an example. Thanks.

EDIT Let's take List<T> as an example, it provides all functions of ArrayList, and it's strongly-typed. So when do we need to use ArrayList? Maybe sometimes it has a better performance? I don't know. I appreciate if you can show me something special of ArrayList.

3

There are 3 answers

5
Jon Skeet On BEST ANSWER

I think it should be considered effectively obsolete for new code, but there's no compelling reason to mark it obsolete and create warnings in all code which was written before 2.0 was released.

In my experience, most of the types and members which have been marked obsolete by Microsoft are actively dangerous in some respect, and should really be fixed if you still have a codebase using them. While using ArrayList is painful and (at least theoretically) prone to discovering type-related bugs at execution time rather than compile time, the type does its job well enough... often there's really no compelling reason to change existing code. It's the kind of change I'd generally consider when I already happened to be working on an area of code which was using ArrayList, rather than actively seeking out every usage of it.

12
xanatos On

It isn't "obsolete" per se. It's "obsolete" as a '70 '80 early '90 car. If I had to choose between a List<Object> and an ArrayList there is a VERY VERY SMALL possibility I would use an ArrayList... Forget it... It doesn't implement IEnumerable<Object>, so to use Linq I would have to use a OfType<Object>().

To make an example:

var aaa = new ArrayList();
var aaaa = aaa.OfType<object>().Where(p => p != null);

var bbb = new List<object>;
var bbbb = bbb.Where(p => p != null);

Someone finally upvoted my response, so I'll add something to it :-)

Had you asked "would you use any non-generic collection" my response would have been different. The Hashtable has an interesting property:

Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable.

So there are places where an Hashtable should be better than a lock + Dictionary or a ConcurrentDictionary (but you would have to benchmark it)

3
Marc Gravell On

Actually it is completely removed from Silverlight - so the intention is there. Presumably there is simply too much old existing code for regular .NET that uses ArrayList to obsolete it, especially since a lot of people run with warnings-as-errors.

You shouldn't use it in new code without good reason.