Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hey, i want to know the class name that call the constructor,
i try with stack trace but didn't work. here is example:

C#
public class ClassA
{
  public ClassB B {get; privet set;}
  
  public ClassA()
  {
    B = new CLassB();
  }
}

public class ClassB
{
  public ClassB()
  {
     //Here i want to print the class name that call to this consructor (ClassA)
  }
}



10x!!
Posted
Comments
Sergey Alexandrovich Kryukov 25-Mar-12 4:21am    
This is pretty simple. I would be curious to know: why?
--SA

The question has little to do with Reflection. This problem is solved using the classes System.Diagnostics.StackTrace and System.Diagnostics.StackFrame.

Please see:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx[^],
http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx[^].

Let's assume you found appropriate stack frame. Use StackFrame.GetMethod to get an instance of the calling method of the type System.Reflection.MethodBase. Please see:
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.aspx[^].

(And yes, this part is Reflection… :-))

You will find the type of the caller using the property System.Reflection.MethodBase.DeclaringType. Please see:
http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.declaringtype.aspx[^].

Everything is pretty simple; it's hard to say where could you have lost. Just read MSDN help pages.

—SA
 
Share this answer
 
v2
Comments
ProEnggSoft 25-Mar-12 8:00am    
Good answer. +5
Sergey Alexandrovich Kryukov 25-Mar-12 13:17pm    
Thank you.
--SA
You do need to use the StackFrame, but you need to access the DeclaringType of the MethodBase class:

C#
StackTrace st = new StackTrace(true);
foreach ( StackFrame sf in st.GetFrames())
    {
    Console.WriteLine(sf.GetMethod().DeclaringType);
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900