views:

76

answers:

2

How to implement interface members "f" with the list?

public interface I
{
    IEnumerable<int> f { get; set; }
}

public class C:I
{
    public List<int> f { get; set; }
}

Error 1 'ClassLibrary1.C' does not implement interface member 'ClassLibrary1.I.f'. 'ClassLibrary1.C.f' cannot implement 'ClassLibrary1.I.f' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'. c:\users\admin\documents\visual studio 2010\Projects\ClassLibrary1\Class1.cs

+5  A: 

You can use a backing field of type List<int> but expose it as IEnumerable<int>:

public interface I
{
    IEnumerable<int> F { get; set; }
}

public class C:I
{
    private List<int> f;
    public IEnumerable<int> F
    {
        get { return f; }
        set { f = new List<int>(value); }
    }
}
Mark Byers
A: 

You can also hide IEnumerable<int> f of I by specifying the interface explicitly.

public class C : I
{
    private List<int> list;

    // Implement the interface explicitly.
    IEnumerable<int> I.f
    {
        get { return list; }
        set { list = new List<int>(value); }
    }

    // This hides the IEnumerable member when using C directly.
    public List<int> f
    {
        get { return list; }
        set { list = value; }
    }
}

When using you class C, there is only one f member visible: IList<int> f. But when you cast your class to I you can access the IEnumerable<int> f member again.

C c = new C();
List<int> list = c.f;   // No casting, since C.f returns List<int>.
Virtlink