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)?
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With