Define the following C# interface:
public interface IShape
{
int NumberOfLineSegments {get;}
int Area {get;}
}
Next, I want to define several rectangle classes: Trapezoid, square,etc. All of these classes differ in their Area() property, but NumberOfLineSegments() always returns 4. Therefore, I would like an ‘interim’ class or interface, called Rectangle (or IRectangle), that looks something like:
public Rectangle : IShape
{
public int NumberOfLineSegments{get{return 4;}}
}
I want Rectangle to implement only NumberOfLineSegment(), and leave it to its derived classes to implement the rest:
public Square : Rectangle
{
public int Area() {get{return length*height;}
}
However, since IShape is an interface, the Rectangle class must implement also Area(), which it knows not how to implement..
Thus I seem to be stuck, either with defining a ‘dummy’ Area() method for Rectangle, or not using inheritence at all.
Is there a way to circumvent this? I have read extensively through Richter’s clr via c#, and in StackOverflow. Thanks in advance!
There are two options.
NotImplementedException), so it does nothing by default until derived.Number 2 is much more preferable, as it forces derived classes to implement the method, whereas in number 1 derived classes are not forced to override base virtual methods.
Abstract methods can successfully satisfy interface definitions as the compiler will know that abstract classes themselves cannot be instantiated, and any derived classes are forced to have the abstract method implemented.
That said, if there are interface members that do not make sense to a particular type, it is usually an indicator to break down your interfaces: