Link to home
Start Free TrialLog in
Avatar of David Bach
David BachFlag for United States of America

asked on

Reference To Name Of Calling Class From Within The Called Class ASP.NET/VB.NET

Greetngs:

I have a Visual Studio Pro 2015 solution containing 1 web project and multiple class libraries all written in VB.NET.

A web page code behind calls class 2 in class library A. Class 2 calls class 5 in class library B.

I need to know the name of class 2, the calling class, from within class 5, the called class.

Is there a way to reference class 2's name?


Much thanks,
David Bach
Avatar of Ark
Ark
Flag of Russian Federation image

Dim st As New StackTrace
Debug.WriteLine("Calling class name: " & st.GetFrame(1).GetMethod.ReflectedType.Name)

Open in new window

Avatar of David Bach

ASKER

Hello Ark:

Thank you for your quick response.

I tried your code snippet, however, I saw the name of the class currently executing and not the name of the calling class.


David
Put this code into child class initializing subroutine (or any method, calling by parent class). Note that GetFrame(1) get first parent method that call child class. You can see stack trace when you get an exception. To enumerate all calls:
Dim strace As New StackTrace(0)
Dim stFrames As StackFrame() = strace.GetFrames()

Dim sf As StackFrame
For Each sf In stFrames
      Debug.WriteLine("Method: {0}", sf.GetMethod())
Next sf

Open in new window

See MSDN for details.
ASKER CERTIFIED SOLUTION
Avatar of Ark
Ark
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you need the class name and you follow the one class per file convention, then you could use the CallerFilePathAttribute to get the filename and then just strip off the path and extension.

If you needed the caller's method name, then you could use the CallerMemberNameAttribute.
Greetings Ark:

I apologize for the delay in closing this question. Your solution is definitely something I can work with.


Much thanks,
David Bach