1

I have an interface IFoo that only gets implemented by objects with a fairly high level (framework) base class. It would be very useful to me to not only get the Interface members, but also the implementing object itself. Would it be bad practice to have the interface include its implementer as a property?

For example:

public interface IFoo
{
  UIElement Implementer {get;}
  int Bar {get;}
}

public class FooTextBox : TextBox, IFoo
{
  public UIElement Implementer
  {    
    get{ return this;}
  }

  public int Bar
  {
    get{ return 5;}
  }
}

and then retrieving it somewhere else:

IFoo foo = GetIFoo();

var opac = foo.Implementer.Opacity;
  • 2
    I don't quite get this. You always have the implementer. There's no need to have a method returning it. Your method returns "this". I don't need a method for that. – gnasher729 Aug 8 '16 at 7:59
  • What's the purpose of KNOWING the concrete implementer? Please describe more clearly. Is the underlying problem related to stackoverflow.com/questions/23242308/… ? – Bernhard Hiller Aug 8 '16 at 8:14
  • Only if you are going to interrogate it for its class and then call methods not available through the interface based on which class is the implementer. Ie If (typeof(Intf.Implementer) is SomeClass) and then something like (SomeClass)Intf.MethodNotAvailableThroughInterface(). That defeats the whole purpose of having interfaces. – Marjan Venema Aug 8 '16 at 17:51
1

No, it is not really a bad practice. There is no problem with this as long as code using the IFoo interface doesn't assume the value returned is not same as value of instance itself. Eg. there is no code that assumes (value as IFoo).Implementer == (value as UIElement) is always true.

For example, instead of user control implementing an interface itself and returning this, there could be separate class (a ViewModel maybe) that returns it's view instead. It is implementer's own detail if it wants return itself or something else.

In your example If you were to rename Implementer to View, it would make much more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.