Ozkan
Ozkan

Reputation: 2041

Convert List<string> to ArrayList

Who knows the easiest way to convert a List of strings to an ArrayList?

I tried setting (ArrayList) before the code but this doesn't do anything.

Upvotes: 23

Views: 50316

Answers (2)

Heinzi
Heinzi

Reputation: 172468

ArrayList has a constructor which accepts an ICollection. Since List<T> implements ICollection, the following should work:

var myArrayList = new ArrayList(myList);

Upvotes: 9

Jon Skeet
Jon Skeet

Reputation: 1503479

Sure:

ArrayList arrayList = new ArrayList(list);

That works because List<T> implements ICollection.

However, I'd strongly advise you to avoid ArrayList (and other non-generic collections) if at all possible. Can you refactor whatever code wants an ArrayList to use a generic collection instead?

Upvotes: 89

Related Questions