Reputation: 14483
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
Reputation: 270860
From your comment:
Derived
will inherit fromBase<Derived>
. In order to createBase<Derived>
you need to haveDerived
, so then you would createDerived
inheritingBase<Derived>
etc. How isBase<Derived>
being created beforeDerived
?
Your misunderstanding starts from here here:
In order to create
Base<Derived>
you need to haveDerived
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 string
s. 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 beforeDerived
?
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