Novikov
Novikov

Reputation: 436

c# Extension method with restriction on MyClass convertation Error

I have got an extension method with restriction on MyClass. What i try to do:

public static void GetXmlDocValues<T>(this List<T> collection, XmlDocument xmlDoc) where T : MyClass
{
     collection.Clear();
     foreach (XmlNode item in xmlDoc.ChildNodes)
     {
         ((List<MyClass>)collection).Add(new MyClass(item));
     }

}

Then Ive got error:

Cannot convert type 'System.Collections.Generic.List<T>' to 'System.Collections.Generic.List<MyProgram.MyClass>'. Here:((List<MyClass>)collection)

Is it possible to do that stuff? Or it makes an error in any case.

Upvotes: 1

Views: 97

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

It looks like you really want your method to look like this:

public static void GetXmlDocValues(this List<MyClass> collection, XmlDocument xmlDoc)
{
    collection.Clear();
    foreach (XmlNode item in xmlDoc.ChildNodes)
    {
        collection.Add(new MyClass(item));
    }
}

There is no need for a generic method if you only want to work with MyClass.

Upvotes: 2

Related Questions