2

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?

1 Answer 1

7

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

And I always wondered what the explicit implementation was good for (I mean besides equal names in different interfaces), just learned something extremely helpful, thanks a lot!

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.