Luke Vo
Luke Vo

Reputation: 20638

Cannot access implemented property (from interface)

I have an interface with properties:

public interface IEntityModifier
{

    ...
    bool AutoDetachOnFinished { get; set; }
    bool Finished { get; }
    ...

}

Then I implement it:

    bool IEntityModifier.AutoDetachOnFinished { get; set; }
    bool IEntityModifier.Finished { get { return this.mFinished; } }

But when I need to access AutoDetachOnFinished within the same class, a compiler error pops out:

    void IEntityModifier.Update(IEntity pEntity, Microsoft.Xna.Framework.GameTime pGameTime)
    {
        if (!this.mFinished)
        {
            this.Value += this.Delta * (float)pGameTime.ElapsedGameTime.TotalSeconds;

            if (this.Value >= this.Max)
            {
                this.Value = this.Max;
                this.mFinished = true;
                if (this.AutoDetachOnFinished) { /* Error Here */ }
            }
        }
    }

The error message:

14 'MEngine.Entities.EntityModifier.SingleValueEntityModifier' does not contain a definition for 'AutoDetachOnFinished' and no extension method 'AutoDetachOnFinished' accepting a first argument of type 'MEngine.Entities.EntityModifier.SingleValueEntityModifier' could be found (are you missing a using directive or an assembly reference?)

I have 2 questions:

  1. Why does the compiler complain if I delete IEntityModifier.s (so IEntityModifier.Update would become Update, apply to any implemented method)?
  2. Why can't I access AutoDetachOnFinished?

Upvotes: 10

Views: 4533

Answers (3)

Zara_me
Zara_me

Reputation: 268

Convert this.AutoDetachOnFinished to object of type IEntityModifier as you are doing explicit Interface implementation. here some explanation.

  IEntityModifier entitymodifier=(IEntityModifier)objectInstanceOfimplementedClass;

     if( entitymodifier.AutoDetachOnFinished)

Upvotes: 1

Because you are implementing the interface explicitly.

bool IEntityModifier.AutoDetachOnFinished { get; set; }

You must cast to the interface in order access explicit implementations. Perhaps not what you want. So remove the interface name from the implementation

bool AutoDetachOnFinished { get; set; }

Upvotes: 4

Oded
Oded

Reputation: 498904

You have implemented these as explicit interface implementations, meaning you can only access them through a variable of the interface type - IEntityModifier.

Either do that:

if (((IEntityModifier)this).AutoDetachOnFinished)

or remove the interface name from the implementation:

bool AutoDetachOnFinished { get; set; }
bool Finished { get { return this.mFinished; } }

Upvotes: 14

Related Questions