Can you get the information which child called constructor in C#?

Viewed 51

I'm trying to get information about which child called parents constructor. I'm not allowed to pass the argument onto the constructor. Is something like this possible?

class Parent {
 Parent() {
  Console.WriteLine("Child1 called me");
 }

}
class Child1: Parent {
 string name;
 Child1(string name) {
  this.name = name;
 }

}
class Child2: Parent {
 string surname;
 Child1(string surname) {
  this.surname = surname;
 }

}
1 Answers

GetType() will still work here, and is non-virtual (which limits how much trouble you can get into re uninitialized fields, which is a problem when calling virtual methods from a constructor); you can always explore the tree if multiple types are involved:

    public Parent()
    {
        var type = GetType();
        while (type != typeof(Parent) && type != null)
        {
            Console.WriteLine(type.Name);
            type = type.BaseType;
        }
    }

If we have:

class Child3 : Child2
{
    public Child3(string surname) : base(surname) { }
}
// ...
new Child3("whatever");

Then this will output:

Child3
Child2
Related