Read private fields using Reflection

Imports System.Reflection
Public Class Form1
    Private myNumber As Integer = 25
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MsgBox(CStr(readPvtInt()))
    End Sub
End Class

Module Module1
    Public Function readPvtInt() As Integer
        Dim frmType As Type = GetType(Form1)
        Dim field As FieldInfo = frmType.GetField("myNumber", BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim frm As New Form1
        Dim pvtValue As Integer = CInt(field.GetValue(frm))
        Return pvtValue
    End Function
End Module

Advertisements