Contango
Contango

Reputation: 80272

How to find the name of the parent class, within a base class in C#?

I inherit a class from a base class "MyLog".

If I call "Write" within the inherited class, I want it to prefix any messages with the name of the inherited class.

As this application needs to be fast, I need some way of avoiding reflection during normal program operation (reflection during startup is fine).

Here is some code to illustrate the point:

class MyClassA : MyLog
{
   w("MyMessage"); // Prints "MyClassA: MyMessage"
}

class MyClassB : MyLog
{
   w("MyMessage"); // Prints "MyClassB: MyMessage"
}

class MyLog
{
  string nameOfInheritedClass;
  MyLog()
  {
    nameOfInheritedClass = ?????????????
  }

  w(string message)
  {       
     Console.Write(nameOfInheritedClass, message);
  }
}

Upvotes: 1

Views: 83

Answers (3)

Jethro
Jethro

Reputation: 5916

I believe you can use GetType() to achive this.

var parentType = this.GetType().BaseType; //Will return MyLog

Where as Jon Skeet pointed out calling Name will return the actual type of the object its called on.

Upvotes: 2

Davide Piras
Davide Piras

Reputation: 44605

try to explore

this.GetType()

properties in the myLog constructor, there you should be able to find type names and other properties of the correct class hierarchy.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500675

I suspect you want:

nameOfInheritedClass = GetType().Name;

GetType() always returns the actual type of the object it's called on.

Upvotes: 5

Related Questions