CFlat
CFlat

Reputation: 71

How to Reimplement ObservableCollection.this[index]

The following does not work as expected: "derived called" is not printed. I am new to C# and probably I am missing some rule.

Thank you.

class Test<T> : ObservableCollection<T>, IList<T>, IList
{
  T IList<T>.this[int index]
  {
    get { Console.WriteLine("derived called"); return default(T); }
    set => throw new NotSupportedException();
  }

  object IList.this[int index]
  {
    get { Console.WriteLine("derived called"); return default(T); }
    set => throw new NotSupportedException();
  }
}
// ...
var t = new Test<int>() { 1 };
int i = t[0];

var oc = (ObservableCollection<int>)t;
int j = oc[0];

Upvotes: 1

Views: 43

Answers (1)

Joe H
Joe H

Reputation: 604

It seems you should just use an ObservableCollection, there is no advantage to what you are trying. Also ObservableCollection inplements IList already so no need to do that.

To do what you expect would be

public class Test<T> : ObservableCollection<T>
{
    public new T this[int i]
    {
        get
        {
            Debug.WriteLine("yo");
            return base[i];
        }
        set { base[i] = value; }
    }
}

But just use an ObservableCollection

Upvotes: 1

Related Questions