Identifying the current class in a class hierarchy

  • Thread starter Thread starter chrisp
  • Start date Start date
C

chrisp

Is there anyway I can get the Type of the class that owns the currently
executing code? I'm trying to get this information for logging purposes. I
have a number of tracing messages throughout a class hierarchy, and I'd like
to be able to log which class a specific trace message has been recorded
from (i.e. is it the base class or is it the instantiated class).

Thanks

Chris
 
Thanks Balasubramanian,

I tried this first, but GetType() returns the type of the instantiated class
not the code class. I'll clarify - from the code below (code is indicative
only) I would want two console messages - one from MyClass and one from
MyBaseClass, but the trace message should include the name of the class the
trace message is created from.

class MyBaseClass
{
virtual void DoIt()
{
Framework.TraceMessage(<class identifier>, "Trace Message");
}
}

class MyClass : MyBaseClass
{
override void DoIt()
{
base.DoIt();
Framework.TraceMessage(<class identifier>, "Trace Message");
}
}

Assume "Framework" is a static class within the assembly. From this code,
its the <class identifier> I'm looking for, so that the
Framework.TraceMessage method to be able to log something like the
following:

[MyBaseClass] Trace Message
[MyClass] TraceMessage

I would prefer to be able to pass something generic (in the same vein as
GetType) to the Framework.TraceMessage method, but I expect this would be
too much. Is it possible to identify the actual to which the code belongs in
C# without resorting to literals?

Thanks, Chris.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top