Reputation: 4516
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
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
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
Reputation: 34200
It sounds as though you want either:
abstract class thing : Graph, IDataTip
) to be used for your parametervoid 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
Reputation: 58980
You could use generic constraints:
public class FooClass<T> where T: Graph, IDataTip
{
public T Foo { get; set; }
}
Upvotes: 6