From base class in C#, get derived type?

C#ReflectionInheritanceTypes

C# Problem Overview


Let's say we've got these two classes:

public class Derived : Base
{
	public Derived(string s)
		: base(s)
	{ }
}

public class Base
{
	protected Base(string s)
	{

	}
}

How can I find out from within the constructor of Base that Derived is the invoker? This is what I came up with:

public class Derived : Base
{
	public Derived(string s)
		: base(typeof(Derived), s)
	{ }
}

public class Base
{
	protected Base(Type type, string s)
	{
		
	}
}

Is there another way that doesn't require passing typeof(Derived), for example, some way of using reflection from within Base's constructor?

C# Solutions


Solution 1 - C#

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Base b = new Base();
            Derived1 d1 = new Derived1();
            Derived2 d2 = new Derived2();
            Base d3 = new Derived1();
            Base d4 = new Derived2();
            Console.ReadKey(true);
        }
    }

    class Base
    {
        public Base()
        {
            Console.WriteLine("Base Constructor. Calling type: {0}", this.GetType().Name);
        }
    }

    class Derived1 : Base { }
    class Derived2 : Base { }
}

This program outputs the following:

Base Constructor: Calling type: Base
Base Constructor: Calling type: Derived1
Base Constructor: Calling type: Derived2
Base Constructor: Calling type: Derived1
Base Constructor: Calling type: Derived2

Solution 2 - C#

GetType() would give you what you're looking for.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncoreView Question on Stackoverflow
Solution 1 - C#JulietView Answer on Stackoverflow
Solution 2 - C#Joe EnosView Answer on Stackoverflow