Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why derive a List<T> class just to restate an indexer?

I keep seeing List derived classes that look something like this

class MyClassList : List<MyClass>
{
    public MyClass this[int index]
    {
        get { return (MyClass)base[index]; }
    }
}

What is the point of this inheritance? It looks like it just restates the casting of the member. I could understand other types of indexer, but this is just a restatement of the default List indexer, and provokes a Visual Studio warning RE: hiding of the base indexer. Is this the right or wrong thing to do, and why?

like image 625
downwitch Avatar asked Jan 18 '23 04:01

downwitch


1 Answers

Perhaps it's a very poor attempt to prevent the overwriting of values via the indexer?

MyClassList x = new MyClassList();
x.Add(new MyClass());
x[0] = new MyClass(); // Error!

Of course, it doesn't stop this:

List<MyClass> x = new MyClassList();
x.Add(new MyClass());
x[0] = new MyClass(); // No problem here...

Basically, it's a bad idea. Poor code abounds, unfortunately - don't infer usefulness from mere existence :(

like image 93
Jon Skeet Avatar answered Jan 28 '23 23:01

Jon Skeet