Get Private Variables using Reflection in VB.NET (URGENT)


I'm not sure if this is possible but here goes...

I know you can use reflection to get the public properties of the current object/class:


But I would like to get the private variables that are defined at the top of the class, see simple example below:

Public Class mySimpleClass

    Private _FirstName As String
    Private _LastName As String

    Public ReadOnly Property Fullname() As String
            Return _FirstName & " " & _LastName
        End Get
    End Property

    Public Sub New()

    End Sub

End Class

I know that example doesn't show much, but basically I know I could access the Property 'FullName' using reflection, however if I want to access the private variables _FirstName and _LastName, how would I go about it? If it's possile at all.
Who is Participating?
Fernando SotoConnect With a Mentor RetiredCommented:
Hi David_Reid_1985;

Yes that can be done. The following code assumes that the class mySimpleClass is part of the executing assembly.

        Dim SimpleClass As New mySimpleClass

        Dim myType As Type = GetType(mySimpleClass)
        Dim fieldInfos() As FieldInfo = myType.GetFields(BindingFlags.NonPublic Or _
            BindingFlags.Instance Or BindingFlags.Static)

        For Each fInfo As FieldInfo In fieldInfos
            Dim fieldName As String = fInfo.Name.PadRight(2)
            Dim fieldType As String = fInfo.FieldType.ToString
            Dim fieldValue As String = fInfo.GetValue(SimpleClass)
            Console.WriteLine("Field name = {0} Field value = {1} Field type = {2}", fieldName, fieldValue, fieldType)

Make them not private?

The whole point of declaring them private means that they can only be accessed and changed inside of the class. If you need to access those variables from outside the class then you want to switch the declaration to Public, or perhaps create a couple more public properties that allow you access to them.
David_Reid_1985Author Commented:
I want to access them from within that class, so in the dispose function I can loop through all private variables setting them to nothing, rather than having to hard code the names of every variable.

Cheers Fernando I will try you suggestion later on today and let you know.

David_Reid_1985Author Commented:
Just tried it, thanks Fernando worked a treat!
Fernando SotoRetiredCommented:
No problem, glad I was able to help. ;=)
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.

All Courses

From novice to tech pro — start learning today.