Reputation: 7128
Lets say that I have a class that represents a Stream
and that I subclass this class to add the methods read and write. These two methods are defined in two separate interfaces IWriteableStream
and IReadableStream
.
public class MyFooStream : Stream, IWriteableStream, IReadableStream
How can I force the developer who subclasses from Stream
to implement the interfaces so that I can enforce the idea that all Stream
must be readable and writeable?
EDIT: So my solution has been to make Stream
abstract and implement the two interfaces. Then the interfaces methods are marked as abstract in Stream
forcing subclasses to implement them.
public abstract class Stream : IWriteableStream, IReadableStream
{
public abstract void WriteToStream();
public abstract void ReadFromStream();
}
public class WaterStream : Stream
{
public override void WriteToStream() {}
public override void ReadFromStream() {}
}
Upvotes: 1
Views: 88
Reputation: 82096
If the interface methods are implemented in the base class then any derivation of Stream
will inherit these and as such already be implementing both IWritableStream
/ IReadableStream
.
If you want to force them to override the default behaviour, then you could make read
/write
methods abstract (or the entire class if need be).
Example
public class MyFooStream : Stream, IWritableStream, IReadableStream
{
public abstract void Write(byte[] data);
public abstract byte[] Read();
}
// if I don't override Write/Read methods the compiler will complain
public class ReadableStream : MyFooStream
{
public override void Write(byte[] data)
{
...
}
public override byte[] Read()
{
...
}
}
Upvotes: 2
Reputation: 3166
Make MyFooStream
an abstract class, and 'implement' those methods on the abstract class as abstract methods - all derived classes will have to have implementations for those methods.
Upvotes: 4