Interface Implementation - Returning Inherited Class
-
I get an error with the compiler each time I try to do this:
public interface IBehavior
{
...
}public interface IBehaviorActing
{
IBehavior Behavior
{
get;
}
}public class Behaviorclass : IBehavior
{
...
}public class Itemclass : IBehaviorActing
{
public Behaviorclass Behavior
{
get {...}
}
}The compiler say the Itemclass does not implement interface (wrong return type - Meaning not defining explicitly
public IBehavior Behavior
in Itemclass). Is there a pattern or another way around this? -
I get an error with the compiler each time I try to do this:
public interface IBehavior
{
...
}public interface IBehaviorActing
{
IBehavior Behavior
{
get;
}
}public class Behaviorclass : IBehavior
{
...
}public class Itemclass : IBehaviorActing
{
public Behaviorclass Behavior
{
get {...}
}
}The compiler say the Itemclass does not implement interface (wrong return type - Meaning not defining explicitly
public IBehavior Behavior
in Itemclass). Is there a pattern or another way around this?Well, you didn't mention your intention why you want to return Behaviorclass in Itemclass. But I would say that I think you can still do whatever you want, using IBehavior return type (instead of Behaviorclass). If you want to use the return type as Behaviorclass (instead of IBehavior), you can up-cast it later, like:
Behaviorclass bc = SomeInstanceofItemclass.Behavior as Behaviorclass;
Hope it helps :) Best Regards, Ferry Mulyono "If you can't bring Mohammed to the mountain, you got to bring the mountain to Mohammed" - Gil Grissom, CSI -
I get an error with the compiler each time I try to do this:
public interface IBehavior
{
...
}public interface IBehaviorActing
{
IBehavior Behavior
{
get;
}
}public class Behaviorclass : IBehavior
{
...
}public class Itemclass : IBehaviorActing
{
public Behaviorclass Behavior
{
get {...}
}
}The compiler say the Itemclass does not implement interface (wrong return type - Meaning not defining explicitly
public IBehavior Behavior
in Itemclass). Is there a pattern or another way around this?The problem is that the interface says the Property has to be of type IBehavior and not Behaviorclass. To have a typesafe accessor in Itemclass and still adhere to the interface do the following: public class Itemclass : IBehaviorActing { public Behaviorclass Behavior { get {...} } IBehavior IBehaviorActing.Behavior { get { this.Behavior; } } } The compiler will call the normal Behavior property whenever you access Behavior via the concrete class. Whenever it is accessed via an interface variable it will access the interface implemenation (which in turn calls the typesafe one). I regulary use these constructs. It's also extremely useful when working with the ICloneable interface.