Friday, November 19, 2010

C# - Retrieve Class name of child instance/executing child

Let's assume we have this parent class:

namespace MyClasses.Test
{
  class Parent
  {
    public Parent()
    {
    }
  }
}

Then we have this child class:

namespace MyClasses.Test
{
  class Child : Parent
  {
    public Child()
    {
    }
  }
}

From what I've tried, there are two ways on how to retrieve the class name, namespace and type of the executing child.

First let's try the long way. :)

using System.Diagnostics;

public Parent()
{
  StackTrace st = new StackTrace(true);
  MethodBase mb = st.GetFrame(1).GetMethod();
  Type type = mb.ReflectedType;
  String className = type.Name;
  String nameSpace = type.Namespace;
}

Or we could try the easy way. :)
public Parent()
{
    Type type = this.GetType().UnderlyingSystemType;
    String className = type.Name;
    String nameSpace = type.Namespace;
}

These will return:

className = "Child"
nameSpace =  "MyClasses.Test"

No comments:

Post a Comment