For compatibility reasons there are still libraries and components which do not use the new generics offered by Visual Studio 2005. This should be no problem as long as you want to use these native collections. But if you need a type safe result list you have to copy all elements one by one to your new generic List.
IList<string> genericList = new List<string>();
foreach (string str in myNativeList)
genericList.Add (str);
Stop! Didn’t we thought that we don’t have to do stupid hand-crafted copy jobs? Yes, but dotNET 2.0 does not offer a quick solution. That is because the new generic List won’t offer an interface that allows you to put in the old IList interface. So let us take a look at the constructor of a generic List.
public List (
IEnumerable<T> collection
)
The idea is to create an adapter that offers the IEnumerable<T> interface in order to allow quick copying the native collection to a generic list. I call it a ListAdapter.
Using this ListAdapter you can convert native collections easily to their generic counterparts without any external copy operations.
IList<string> genericList = new List<string> (
new ListAdapter<string> (myNativeList)
);
You can download the implementation of the ListAdapter using the following link:
Copying a native untyped IList to a generic List
Hope that this piece of code makes your life easier.
Cheers
Gerhard
PS: At this place I won’t forget to say thanks to Mr. Alexander Jung for his idea to the ListAdapter
July 31, 2006 at 6:35 am
Very useful, thanks for snippet!
September 13, 2006 at 2:55 pm
Gerhard, Thanks for the code.
With Lutz Roeder’s reflector, you can see the code of the constructor of List(IEnumerable collection).
Indeed is the way you coded it fine.
September 13, 2007 at 2:27 pm
[...] The AdFactum ObjectMapper .NET provides a helper class called ListAdapter to bridge the gap between the untyped IList interface and the Generics, used by the dotNet Framework 2.0. The base principles of the ListAdapter can be found here. [...]
May 30, 2008 at 9:43 pm
Thanks for the code !