Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract getter with concrete setter in C#

Tags:

c#

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?

like image 337
Wesley Hill Avatar asked Dec 15 '10 08:12

Wesley Hill


2 Answers

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);
   }
 }
like image 191
m0sa Avatar answered Sep 24 '22 00:09

m0sa


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.

like image 39
Ignacio Soler Garcia Avatar answered Sep 23 '22 00:09

Ignacio Soler Garcia