From base class in C # get derived type?

Say we have 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 the Base constructor that Derived is an invoker? Here 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 does not require passing typeof(Derived) , for example, somehow using reflection inside the Base constructor?

+44
inheritance reflection c # types
Jun 09 '09 at 21:03
source share
2 answers
 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 displays 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 
+77
Jun 09 '09 at 21:11
source share

GetType() will give you what you are looking for.

+27
Jun 09 '09 at 21:12
source share



All Articles