C# – Extension method not found (not an assembly reference issue)

cextension-methodslinq

I have the following extension method:

public static EntitySet<T> ToEntitySetFromInterface<T, U>(this IList<U> source)
    where T : class, U
{
    var es = new EntitySet<T>();
    IEnumerator<U> ie = source.GetEnumerator();
    while (ie.MoveNext())
    {
        es.Add((T)ie.Current);
    }
    return es;
}

and Im attempting to use it as follows:

   List<IItemMovement> p = new List<IItemMovement>();
    EntitySet<ItemMovement> ims = p.ToEntitySetFromInterface<ItemMovement, IItemMovement>();

where ItemMovement implements IItemMovement. The compiler complains:

'System.Collections.Generic.List' does not contain a
definition for 'ToEntitySetFromInterface' and no extension method
'ToEntitySetFromInterface' accepting a first argument of type
'System.Collections.Generic.List' could be found (are
you missing a using directive or an assembly reference?)

No I'm not missing a reference. If I just type the name of the static class containing the method it pops up and so does the extension method. Thnx

Best Answer

This code works for me, and its a direct copy of your code, minus the ItemMovement and its interface, so perhaps something is wrong with that part?

public class TestClient
{
    public static void Main(string[] args)
    {
        var p = new List<IItem>();
        p.Add(new Item { Name = "Aaron" });
        p.Add(new Item { Name = "Jeremy" });

        var ims = p.ToEntitySetFromInterface<Item, IItem>();

        foreach (var itm in ims)
        {
            Console.WriteLine(itm);
        }

        Console.ReadKey(true);
    }
}

public class Item : IItem
{
    public string Name { get; set; }
    public override string ToString()
    {
        return Name;
    }
}

public interface IItem
{
}

public static class ExtMethod
{
    public static EntitySet<T> ToEntitySetFromInterface<T, U>(this IList<U> source) where T : class, U
    {
        var es = new EntitySet<T>();
        IEnumerator<U> ie = source.GetEnumerator();
        while (ie.MoveNext())
        {
            es.Add((T)ie.Current);
        }
        return es;
    }
}