Geeks With Blogs

News My Blog has been MOVED to
Michael Freidgeim's OLD Blog My Blog has been MOVED to

We are writing new code using generic List<> , e.g. List<MyClass>.
However we have legacy functions, that are expect ArrayList as a parameter.
It is a second time, when I and my colleague asked, how to "cast" generic List<MyClass> to ArrayList.
The answer is simple- just use ArrayList constructor with ICollection parameter.
Note that it is not real cast, it  copies  references to ArrayList.

var list=new List<MyClass>();

//Fill list items

ArrayList al=new ArrayList(list);//"cast"- 

If you need opposite operation -Convert ArrayList to a Generic List,
you can filter all elements of arrayList that can be cast to the same type using Enumerable.OfType(Of TResult) Method
List<MyClass> typedList = arrayList.OfType<MyClass>().ToList();




Posted on Saturday, June 5, 2010 9:10 PM .Net Framework | Back to top

Comments on this post: How to "cast" from generic List<> to ArrayList

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Michael Freidgeim | Powered by: