Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> to IEnumerable<T> problem in interface

Tags:

c#

namespace WpfApplication3
{
public class Hex
{
    public String terr;
}    

public class HexC : Hex
{
    int Cfield;
}

public interface IHexGrid
{
    IEnumerable<Hex> hexs { get; }
}

public class hexGrid : IHexGrid //error CS0738: 'WpfApplication3.hexGrid' does not               
{
    public List<Hex> hexs { get; set; }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        List<HexC> hexList1 = new List<HexC>();
        genmethod(hexList1); //but this compiles fine          
    }

    void genmethod(IEnumerable<Hex> hexList)
    {
        string str1;
        foreach (Hex hex in hexList)
            str1 = hex.terr;            
    }
}
}

The full error message is: 'WpfApplication3.hexGrid' does not implement interface member 'WpfApplication3.IHexGrid.hexs'. 'WpfApplication3.hexGrid.hexs' cannot implement 'WpfApplication3.IHexGrid.hexs' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'.

Why doesn't List implicitly cast to IEnumerable above? Thanks in advance!

like image 711
Rich Oliver Avatar asked Oct 20 '25 10:10

Rich Oliver


2 Answers

That kind of casting (covariance?) doesn't apply to class/interface declarations. It can only be done on parameters and return types.

The compiler is looking for the exact signature, isn't finding it, and rightly saying you didn't implement the member. The property/method signature must match exactly.

This answer actually sums it up better than I could explain.

like image 160
Christopher Currens Avatar answered Oct 22 '25 23:10

Christopher Currens


Christopher has the right answer, but you could easily work around this by having a private property be the actual list and then the getter on the hexGrid just return the casted IEnumerable interface from the List.

public class hexGrid : IHexGrid               
{
    private List<Hex> _hexs { get; set; }
    public IEnumerable<Hex> hexs
    {
       get { return _hexs as IEnumerable; }
       set { _hexs = new List<Hex>( value ); }
    }
}
like image 24
Jordan Parmer Avatar answered Oct 22 '25 23:10

Jordan Parmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!