Use Reflection to access Friend Function with

Good Morning! First let me throw a shout out to Brian K. Woytovich who has a very cool, real to life blog. I encourage you to visit and hear what he has to say.

My topic today is one that I have been meaning to blog about.. Like yesterday’s blog entry sometimes we need to find a better way to access methods and properties of classes without loops. So we want to access a friend function of another class by using reflection. So here it is and make it a great day.

Imports System.Reflection
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim tc As New TestClass()
        Dim tcSayHello As MethodInfo = tc.GetType().GetMethod("SayHello", _
                                                    BindingFlags.NonPublic Or BindingFlags.Instance)
        tcSayHello.Invoke(tc, Nothing)
        Dim tcGetMessage As MethodInfo = tc.GetType().GetMethod("GetMessage", _
                                                      BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim params() As Object = {"Kelly Martens"}
        MessageBox.Show(tcGetMessage.Invoke(tc, params))
    End Sub
End Class
Public Class TestClass
    Friend Sub SayHello()
    End Sub
    Friend Function GetMessage(ByVal name As String) As String
        Return "Hello " & name
    End Function
End Class
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: