Andrija
Andrija

Reputation: 14483

Deriving class from class that is using generic of derived class

I do not understand why does this code work. Derived class is inheriting from Base class that is using Derived class type. I would have expect some king of infinite loop in type creation.

Please can someone explain why does this code work? Thank you.

using System;
using System.Collections.Generic;
using static System.Console;

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            WriteLine(new Derived(new Internal<Derived>()));

            ReadLine();
        }
    }

    public class Base<T>
    {
        public Base(Internal<T> intern)
        {
            this.Intern = intern;
        }

        public Internal<T> Intern { get; private set; }
    }

    public class Internal<T>
    {
    }

    public class Derived : Base<Derived>
    {
        public Derived(Internal<Derived> intern)
            : base(intern)
        {
        }
    }
}

Upvotes: 1

Views: 88

Answers (1)

Sweeper
Sweeper

Reputation: 270860

From your comment:

Derived will inherit from Base<Derived>. In order to create Base<Derived> you need to have Derived, so then you would create Derived inheriting Base<Derived> etc. How is Base<Derived> being created before Derived?

Your misunderstanding starts from here here:

In order to create Base<Derived> you need to have Derived

That is not true. You might think that to create T<U> you must need an instance of U first.

Take List<string> as an example. I can create an List<int> without using any instances of string:

var list = new List<string>();

list does not contain any strings. It's just an empty list. The same thing applies here.

To create a Base<Derived>, you need an Internal<Derived>, which you have by doing new Internal<Derived>(). Internal<Derived> also does not require an instance of Derived to be created by the same logic.

What is really happening here is you are trying to create an instance of Derived. You call its constructor, which calls Base<Derived>'s constructor with an instance of Internal<Derived>.

How is Base<Derived> being created before Derived?

If you think about it, it kind of makes sense to have base classes created before derived classes. To create a Cat, you create an Animal first, and then you add all the Cat-specific features to it.

Upvotes: 2

Related Questions