locked
How to get Calling Class name in called class RRS feed

  • Question

  • Hi,

       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

    please help me buddies...

     


     

     


    Thanks - Ravi

    Friday, August 19, 2011 2:36 PM

Answers

  • Try the following

     

     

    Dim stackTractObject As New StackTrace

    Debug.WriteLine("Calling class name: " & stackTractObject.GetFrame(1).GetMethod.ReflectedType.Name)

     

    Tell me this is what you want.

     

     



    • Proposed as answer by DiegoCattaruzza Friday, August 19, 2011 3:35 PM
    • Marked as answer by Ravi_P Saturday, August 20, 2011 11:33 AM
    Friday, August 19, 2011 3:18 PM

All replies

  • Try the following

     

     

    Dim stackTractObject As New StackTrace

    Debug.WriteLine("Calling class name: " & stackTractObject.GetFrame(1).GetMethod.ReflectedType.Name)

     

    Tell me this is what you want.

     

     



    • Proposed as answer by DiegoCattaruzza Friday, August 19, 2011 3:35 PM
    • Marked as answer by Ravi_P Saturday, August 20, 2011 11:33 AM
    Friday, August 19, 2011 3:18 PM
  • I dont think you can do that. Consider

    1. Adding a constructor to Class1 that takes an object and stores it as a private variable. Lets call it CallerObject.

    2. Instantiate Class1 using this constructor and pass Me as the argument.

    3. In the Class1, CallerObject.GetType() should give you the class type.

    Friday, August 19, 2011 3:19 PM
  • Hi Amolpbhavsar,

     

     

      Thanks u very much. this is what i want exactly...   Its working perfectly...

     

     

     

     

     

     

     


    Thanks - Ravi
    Saturday, August 20, 2011 11:33 AM