Friday, August 26, 2011

Getting Calling Class name in called class in .NET

Getting Calling Class name in called class in .NET

Question :

  I want to get the calling class name from Called class.
here calling class is Form1 and Called Class is Class1. 
I'm calling Test() function of Class1 from Form1, now in test() function i want to get the calling function that is Form1 .
Important thing is that I want to get without passing any parameters that is i don't want to change any signature of the function because its already completed projects,so this function has lot of references. so i want to get calling class name without changing / adding additional parameters..
ex :
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cls As New Class1
        cls.test()
    End Sub
End Class
Public Class Class1
    Public Sub test()
        '' HERE I WANT TO GET CALLING CLASS NAME i.e Form1
    End Sub
End Class

Answer :

Public Class Class1
    Public Sub test()
        '' HERE I WANT TO GET CALLING CLASS NAME i.e Form1

    Dim stackTractObject As New StackTrace

    Msgbox(stackTractObject.GetFrame(1).GetMethod.ReflectedType.Name)

    End Sub
End Class

No comments:

Post a Comment