tags:

views:

159

answers:

2

Is it possible in C# to define return type of a method as some class that additionally implement some interface?

For example, in GTK# application I would like to have a widget to display documents. I would like to provide several implementations of that widget - one based on Gecko, one on Webkit and one, basic,on regular Gtk.TextView. Clearly, all those classes have to inherit from Gtk.Widget (indirectly). I would declare an interface that all those widgets would implement. Last, I would create a factory method that would create appropriate widget, based on eg. available libraries. What type should factory method return?

interface IDocumentView {...};

class GeckoDocumentView : Gecko.Webcontrol, IDocumentView {...};

class WebKitDocumentView : WebKit.WebView, IDocumentView {...};

class BasicDocumentView : Gtk.TextView, IDocumentView {...};

class DocumentViewFactory {
    static IDocumentView CreateView () {...};
}

What should be return type of DocumentViewFactory.CreateView method? If it's not possible to specify both Gtk.Widget and IDocumentView, should it be:

  • Gtk.Widget (base class), which will be later casted to IDocumentView?
  • IDocumentView (interface), which will be later casted to Gtk.Widget?

EDIT - can interface force inheriting from specific base class?

+4  A: 

I like to keep platform code (which GTK# falls under) out of my code as much as possible.

Given that, I would prefer to return IDocumentView.

This way, your code will use the IDocumentView interface and your platform plumbing code can use the Gtk.* classes.

Frank Krueger
+1  A: 

Try to use Abstract Factory Pattern.

JMSA