I was just looking into the implementation of classes such as JToken
and I noticed it inherits from List<JToken>
I'd never seen a class inherit form a list before so after reading "Avi Turners" answer to this question: Why and when to inherit from Collection<T> I sort of understood. I could understand that it might be nice to make a class a collection and override methods for Collection
to give them there own implementation.
So I created a few dummy classes to try and get an understanding of what .net will allow me to do with this. So I wrote:
public class A : Collection<A>
{
public int @Integer { get; set; }
public string @String { get; set; }
public void Remove(int index)
{
RemoveItem(index);
}
protected override void RemoveItem(int index)
{
}
}
public class B
{
public B()
{
var a = new A
{
new A(),
new A()
};
a.Integer = 1;
a.String = "";
var firstItem = a[1];
a.Remove(2);
}
}
This confirmed that it would allow to inherit a list of itself. This I don't understand. Why can I have A be a class that I can assign properties, whilst A is also a list where I can add elements of A (where these new instances can also be lists or just a collection again).
shouldn't there be a class A that is only a class, and another class that is a collection (for instance public class ACollection: Collection<A>
)
I can't imagine where this would be necessary, so why does it not display an error.
I realize that I am probably looking at this from the wrong angle, and using it completely wrong. But I couldn't find many resources and none of them seemed to help.
Could anyone provide examples of why this would be useful/allowable?
Thanks.