Fabian Tamp
Fabian Tamp

Reputation: 4516

Class member of Interface and base class

I've got a base class called Graph and an interface called IDataTip.

I've got a number of classes that implement both of these, for example:

class TreeGraph : Graph, IDataTip
{
  //interface implementation
}

I was wondering if there was a way to declare a member of another class such that the type of the member requires classes that match both the abstract class and the interface?

For example, in the following class:

class GraphExporter
{
    public Object GraphWithDataTip {set; get;}
}

I would like to be able to replace the Object type with something that indicates that GraphWithDataTip should be inherit from Graph and implement IDataTip. Is there any way to do this? Or if not, could somebody recommend a more sensible design?

Thanks in advance!

Upvotes: 2

Views: 156

Answers (4)

Maarten
Maarten

Reputation: 22945

I'm assuming you mean a derived class of your base class? Is this what you mean?

public abstract class Graph {
    public abstract void SomeMethod();
}

public interface IDataTip {
    void SomeMethod();
}

public class MyClassDerivedFromGraph: Graph, IDataTip {
    void SomeMethod() {
       // This method matches both the interface method and the base class method.
    }
}

Upvotes: 0

pdriegen
pdriegen

Reputation: 2039

You can define an interface that both Graph and IDataTip implement, and then have your member of another class be an instance of that new interface.

//new interface
interface IGraphAndDataTip
{
}

class Graph : IGraphAndDataTip
{
}

interface IDataTip : IGraphAndDataTip
{
}

class AnotherClass
{
    //implements both graph and IDataTip
    IGraphAndDataTip MyMember;
}

Upvotes: 0

Dan Puzey
Dan Puzey

Reputation: 34200

It sounds as though you want either:

  • a new base type (abstract class thing : Graph, IDataTip) to be used for your parameter
  • a generic method of the form void MyMethod<T>(T thing) where T : Graph, IDataTip

Alternatively, you could cast the parameter within your method and throw an exception if it's not suitable, but this would be a runtime-only check.

Upvotes: 4

Daniel Mann
Daniel Mann

Reputation: 58980

You could use generic constraints:

public class FooClass<T> where T: Graph, IDataTip
{
    public T Foo { get; set; }
}

Upvotes: 6

Related Questions