C# Error CS0738 when class inherits from interface and with type that inherits from interfce type method

Viewed 217

I got CS0738 when class impelments an interface, and interface has a method, with return type interface.

And in class return type is a struct that implements return type interface.

Simply, this code shows the problem:

public interface IGame
{
    IPlayer WhoWin();
}

public interface IPlayer
{
    int ID { get; }
}

And in class:

public class MyGame : IGame
{
    // ERROR CS0738
    public MyPlayer WhoWin()
    {
        // ...
        return null;
    }
}

public class MyPlayer : IPlayer
{
    public int ID 
    {
        get
        {
            return ColorTranslator.ToWin32(Color);
        }
    }
    public Color Color;
}

What should I do? How can I solve the problem?

2 Answers

Change the return type of WhoWin from MyPlayer to IPlayer in your MyGame class then it should work.

public class MyGame : IGame
{
    // CHANGE THIS TO IPlayer like here:
    public IPlayer WhoWin()
    {
        // ...
        return null;
    }
}

public class MyPlayer : IPlayer
{
    public int ID 
    {
        get
        {
            return ColorTranslator.ToWin32(Color);
        }
    }
    public Color Color;
}

You can make IGame generic interface and apply where T : IPlayer constraint

public interface IGame<out T> where T : IPlayer
{
    T WhoWin();
}

Then implement it like

public class MyGame : IGame<MyPlayer>
{
    public MyPlayer WhoWin()
    {
        // ...
        return null;
    }
}
Related