I'm trying to write an abstract base class for read-only collections which implement IList
. Such a base class should implement the set-indexer to throw a NotSupportedException
, but leave the get-indexer as abstract. Does C# allow such a situation? Here's what I have so far:
public abstract class ReadOnlyList : IList {
public bool IsReadOnly { get { return true; } }
public object this[int index] {
get {
// there is nothing to put here! Ideally it would be left abstract.
throw new NotImplementedException();
}
set {
throw new NotSupportedException("The collection is read-only.");
}
}
// other members of IList ...
}
Ideally ReadOnlyList
would be able to implement the setter but leave the getter abstract. Is there any syntax which allows this?
Delegate the work to protected members which you can then mark as abstract or virtual depending on the desired behaviour. Try something like this:
// implementor MUST override
protected abstract object IndexerGet(int index);
// implementor can override if he wants..
protected virtual void IndexerSet(int index, object value)
{
throw new NotSupportedException("The collection is read-only.");
}
public object this[int index] {
get {
return IndexerGet(index);
}
set {
IndexerSet(index, value);
}
}
No, you cannot have a property with a member abstract and the other implemented. What I would do is to set the whole property as abstract and redefine it at the inheritors to do whatever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With