0

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.

Kieran
  • 612
  • 6
  • 22
  • 2
    You have discovered a form of the [Curiously Recurring Template Pattern](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern). (My favourite name for a pattern ever!) NOTE: The C# version isn't really the same as the C++ one, but it definitely has similarities. – Matthew Watson May 17 '18 at 14:27
  • thank you, I will give that a read. – Kieran May 17 '18 at 14:29
  • 1
    [Here's a more understandable article about the C# version.](http://zpbappi.com/curiously-recurring-template-pattern-in-csharp/) – Matthew Watson May 17 '18 at 14:30
  • Ah, thanks. I'll look at that also. – Kieran May 17 '18 at 14:32

1 Answers1

1

Don't wrap your head around such a freaks. It does not make that much use, nor makes your intention clearer. Indeed, it is better to have class A and class ACollection : ICollection<A> separated for many, many, many reasons.

Zazaeil
  • 3,900
  • 2
  • 14
  • 31