Guilherme Carvalho
Guilherme Carvalho

Reputation: 330

Problem with C# interfaces and inheritance

I have the following interface I want to implement in a class:

public interface IAgro {
     AgroState agroState { get; }
}

The problem is that instead of implementing AgroState in the class using the interface I want my property to implement a different class which inherits from AgroState

public class E1_AgroState : AgroState
{
...
}

public class BasicWalkingEnemy : Entity, IAgro
{
    public E1_AgroState agroState { get; }

}

This is something I am used to do in Swift with protocols, for example, but C# compiler complains with

'BasicWalkingEnemy' does not implement interface member 'IAgro.agroState'. 'BasicWalkingEnemy.agroState' cannot implement 'IAgro.agroState' because it does not have the matching return type of 'AgroState'. [Assembly-CSharp]csharp(CS0738)

For now one solution I found is doing it like:

public class BasicWalkingEnemy : Entity, IAgro
{
    public AgroState agroState { get { return _agroState; } }
    public E1_AgroState _agroState { get; private set; }
}

But I think that is very inelegant. Is there a better solution to my problem?

Upvotes: 2

Views: 212

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

Typically the way you'd do this is with explicit interface implementation so that anyone who only knows about your object via IAgro will just see AgroState, but any code that knows it's working with BasicWalkingEnemy will get E1_Agrostate:

// Note: property names changed to comply with .NET naming conventions
public class BasicWalkingEnemy : Entity, IAgro
{
    // Explicit interface implementation
    AgroState IAgro.AgroState => AgroState;

    // Regular property
    public E1_AgroState AgroState { get; private set; }
}

Upvotes: 7

Related Questions