0

I have an interface say public interface IofMine{} and code like this:

interface IItems
{
    List<IofMine> MyList;
}

public class Items: IItems{
    private List<IofMine> _myList;
    public List<IofMine> MyList
        {
            get{return _myList;}
            set{_myList = value;}
        }
}

public class ofMine : IofMine
{}

...

Some where in say main I call this functions add1 and add2 tat look like this:

...
public static void add1<T>(Items items) where T : IofMine, new()
{
    var temp = items.MyList;
    var toAdd = new List<T>();
    temp.AddRange(toAdd); // here it talls me :  Error Argument 1: cannot convert from 'System.Collections.Generic.List<T>' to 'System.Collections.Generic.IEnumerable<IofMine>'
}

public static void add2<T>(Items items) where T : IofMine, new()
{
    var toAdd = new List<T>();
    toAdd.AddRange(items.MyList); // here it talls me :  Error Argument 1: cannot convert from 'System.Collections.Generic.List<IofMine>' to 'System.Collections.Generic.IEnumerable<T>'
}

So I wonder how to make list from interface be expandable with list from generic template that my function received and vice versa?

myWallJSON
  • 9,110
  • 22
  • 78
  • 149
  • problem is in my case I instantiate `toAdd` list from LINQ select `...Select((p, i) => new T{ /*...*/ }).ToList();` and that I cant add to the original given collection. – myWallJSON Jul 23 '12 at 05:12

2 Answers2

0

Instantiate your toAdd variables as List, not List. So where you have the lines:

var toAdd = new List<T>();

in your methods, change them to this:

var toAdd = new List<IofMine>();
Nasai
  • 93
  • 1
  • 11
  • problem is in my case I instantiate `toAdd` list from LINQ select `...Select((p, i) => new T{ /*...*/ }).ToList();` and that I cant add to the original given collection. – myWallJSON Jul 23 '12 at 05:09
0

You cannot cast a class implementing an interface from a Generic class directly. One solution would be to cast in object or to use dynamic in .NET 4.0:

public static void add1<T>(Items items) where T : IofMine
{
        List<T> temp = (List<T>)(object)items.MyList;
        var toAdd = new List<T>();
        ofMine of = new ofMine() { i = 0 };
        toAdd.Add((T)(IofMine)of);
        temp.AddRange(toAdd);
}

If you want some explanation of this decision from Microsoft developers, you can find it here: Generics in C# - Cannot convert 'classname' to 'TGenericClass'

Hope this helps.

Community
  • 1
  • 1
linvi
  • 115
  • 1
  • 7