Unable to access the implemented property (from the 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 inside one class, a compiler error appears:

  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 */ } } } } 

Error message:

14 'MEngine.Entities.EntityModifier.SingleValueEntityModifier' does not contain a definition for "AutoDetachOnFinished" and there is no extension to the "AutoDetachOnFinished" method that takes the first argument of the type "MEngine.Entities.EntityModifier.SingleValueEntityModifier" the link may or may not be ?)

I have 2 questions:

  • Why IEntityModifier. compiler complain if I IEntityModifier. (therefore IEntityModifier.Update will become Update , applicable to any implemented method)?
  • Why can't I access AutoDetachOnFinished ?
+8
syntax c #
source share
3 answers

You implemented them as explicit interface implementations , that is, you can access them only through an interface type variable - IEntityModifier .

Or do this:

 if (((IEntityModifier)this).AutoDetachOnFinished) 

or remove the interface name from the implementation:

 bool AutoDetachOnFinished { get; set; } bool Finished { get { return this.mFinished; } } 
+12
source share

Because you are implementing the interface explicitly.

 bool IEntityModifier.AutoDetachOnFinished { get; set; } 

You must point to an interface to access explicit implementations. Perhaps not what you want. Therefore, remove the interface name from the implementation

 bool AutoDetachOnFinished { get; set; } 
+2
source share

Convert this.AutoDetachOnFinished to an object of type IEntityModifier as you are executing an explicit interface implementation. here is an explanation.

  IEntityModifier entitymodifier=(IEntityModifier)objectInstanceOfimplementedClass; if( entitymodifier.AutoDetachOnFinished) 
+1
source share

All Articles