Search

Mar 14, 2008

Cannot convert type 'System.Collections.Generic.List<

I have one problem while working with Generic collection. I am returning the generic collection of base class, which at the end assigned to child class.


List<Child> childs = SelectAll();

Here is the defination of SelectAll();


public override List<MyParent> SelectAll()

While doing this I got an error....

Cannot implicitly convert 'System.Collections.Generic.List<MyParent>' to 'System.Collections.Generic.List<Child>'

Because, the returning collection is of MyParent and I need to store it into collection of Child.

Here is the solution.

Generic collection List<> provider one Generic method called ConvertAll

ConvertAll: Converts the elements in the current List<(Of <(T>)>) to another type, and returns a list containing the converted elements.

Here is the code,

List childs = SelectAll().ConvertAll<child>(ParentToChild);

and here is the ParentToChild method.

public static Child ParentToChild(MyParent myParent)
{
return (Child)myParent;
}


Read more..

No comments: