1

I'm getting an error. Here's the code copied across to a Console project and stripped down:

namespace ConsoleApplication1
{
public interface IHexGrid
{ 
    IEnumerable<Hex> hexs { get; } //error related location
}

public class HexC : Hex
{ public int var1;}

public abstract class Hex
{ public int var2; }    

public class HexGridC : IHexGrid //error CS0738
{        
    public List<HexC> hexs { get; set; } // error related location
}    

class Program
{        
    static void Main(string[] args)
    {
    }
}
}

I'm getting the following: error CS0738:

'ConsoleApplication1.HexGridC' does not implement interface
member 'ConsoleApplication1.IHexGrid.hexs'. 'ConsoleApplication1.HexGridC.hexs' cannot 
implement 'ConsoleApplication1.IHexGrid.hexs' because it does not have the matching 
return type of '`System.Collections.Generic.IEnumerable<ConsoleApplication1.Hex>`'.

Not sure why as IENumerable is Covariant. Any help much appreciated.

Edit: the code has been simplified

1
  • 2
    Honestly, that compilation error message cannot get much better than this... it tell you exactly what to do :) Commented Oct 4, 2011 at 6:05

1 Answer 1

4

The problem is that your property is of the wrong type. C# doesn't support covariant return types for properties or methods specified in interfaces or for virtual method overriding. You can use explicit interface implementation though:

public class HexGridC : IHexGrid //error CS0738: etc
{        
    public GridElList<HexC> hexs { get; set; } // error related location

    IEnumerable<Hex> IHexGrid.hexs { get { return hexs; } }
}

As an aside, this all seems terribly complicated code - and it's generally not a good idea to derive from List<T> in the first place. (Favour composition, or derive from Collection<T> which is designed for inheritance.) Does it really need to be so complicated? If it does, it would still have been worth cutting down the complexity of the example for the sake of the question.

Sign up to request clarification or add additional context in comments.

1 Comment

I believe it does need to be that complicated, but apologies for not simplifying the question further at the start. I had forgotten about the interface property limitation. I guess you could use a different property name and just make an explicit return in the get, but using explicit interface implementation is really neat! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.