Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is casting an IEnumerable to an ArrayList O(N) or O(1)?

When I do this cast:

private IEnumerable objects;
ArrayList castedObjects = (ArrayList)objects;

Is this a "direct" cast, or the enumerable is converted into an ArrayList via an internal method (that presumably loops through all the elements)?

like image 902
vulkanino Avatar asked Jan 20 '23 13:01

vulkanino


2 Answers

This is either a "direct" cast (if the underlying object is actually an instance of ArrayList), or you'll get an exception. No implicit creating of an ArrayList object is done "behind the scene".

like image 151
Vlad Avatar answered Jan 22 '23 02:01

Vlad


This is a direct cast. It will only work if the object is an ArrayList already, for example:

IEnumerable objects = new ArrayList();
ArrayList castedObjects = (ArrayList)objects;

If the object is not an ArrayList but some other object that implements IEnumerable, the cast will fail.

You can create an ArrayList from an ICollection, for example:

ICollection objects = new string[] { "a", "b" };
ArrayList castedObjects = new ArrayList(objects);

This will loop through the collection and copy the items to the ArrayList, so it's an O(n) operation.


Generally you should not use the ArrayList class at all, but the generic List<T> class that offers strict typing.

like image 30
Guffa Avatar answered Jan 22 '23 04:01

Guffa