• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 218
  • Last Modified:

retrieving the instance of the calling object?

is it possible to get the calling class and use it in the called module?
for example
class A is calling method modifyC in class B
modifyC takes a param from the calling class

basically I need to clean up some code that has method repeated in multiple classes and want to pull those out but need to use a variable from the calling member

is the easiest way to create an enum with the classes that could be calling and go that route?

thanks for the help
  • 2
  • 2
2 Solutions
Mike TomlinsonMiddle School Assistant TeacherCommented:
You could make a "sender" parameter like .Net does...

    Private Sub Foo(ByVal sender As Object, ByVal someParam As Integer)
        If TypeOf sender Is ClassA Then
            Dim clsA As ClassA = CType(sender, ClassA)
            ' do something with "clsA"
        ElseIf TypeOf sender is ClassB Then
        Else ...
        End If
    End Sub

Or if you want to be able to use the exact same calling code for all forms then create an Interface and make all your forms implement it.  Then the data type of your parameter should be the Interface type so you can access the common property/sub/function of them all.
Orlando15767Author Commented:
How could I go about using an interface to accomplish this? I've never used interface that much, and never in vb.net

Bob LearnedCommented:
Something like this:

    Public Interface IFooBar
         Sub MethodA
    End Interface


   Public Class FooBarTest
      Implements IFooBar

      Private _test As String = ""
      Public Property StringValue() As String
             Return _test
          End Get
          Set(ByVal value As String)
             _test = value
          End Set
      End Property

      Private Sub MethodA() Implements IFooBar.MethodA
      End Sub

   End Class


   Dim instance As New FooBarTest
   instance.StringValue = "Bob"

   Dim test As IFooBar = CType(instance, IFooBar)
Mike TomlinsonMiddle School Assistant TeacherCommented:
Thanx Bob.  =)

So once you have Implemented the Interface, that class can take the place of a parameter specifed as that Interface type:

    Private Sub Foo(ByVal sender As IFooBar)
    End Sub

You can create an instance of FooBarTest and pass that into Foo():

    Dim instance As New FooBarTest
    instance.StringValue = "Bob"

This will work with ANY class that Implements IFooBar...
Bob LearnedCommented:
Any time Mike ;)

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now