Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

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

Looping through the variables (properties?) of a class

How can I loop through the variables inside a class?

I have a class such as:

Public Class MyTestClass
  Public DataField1 as string
  Public DataField2 as integer
End Class

I want a function that allows me to loop through the class and get a list with DataField1 and Datafield2 (and the data type if possible).  Anyone tell me how to do this?

Thanks!! Rob
1 Solution
Mike TomlinsonMiddle School Assistant TeacherCommented:
You can use reflection to get fields, properties, methods, events, etc...

Here is an example:

Public Class MyTestClass
    Private _DataField1 As String
    Public Property DataField1() As String
            Return _DataField1
        End Get
        Set(ByVal Value As String)
            _DataField1 = Value
        End Set
    End Property

    Public DataField2 As Integer
    Private PrivateDataField3 As Integer
End Class

Imports System.Reflection
Public Class Form1
    Inherits System.Windows.Forms.Form

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListProperties(New MyTestClass)
    End Sub

    Private Sub ListProperties(ByVal o As Object)
        Dim p As String
        Dim pi As PropertyInfo
        Dim pis() As PropertyInfo = o.GetType.GetProperties
        For Each pi In pis
            If pi.CanRead Then
                p = "Read"
            End If
            If pi.CanWrite Then
                If p = "" Then
                    p = "Write"
                    p = p & "/Write"
                End If
            End If
            p = p & " Property " & pi.Name & "() of Type " & pi.PropertyType.ToString

        Dim fi As FieldInfo
        Dim fields() As FieldInfo = o.GetType.GetFields()
        For Each fi In fields
            Debug.WriteLine("Field: " & fi.Name)
    End Sub

End Class

rbertkeAuthor Commented:
yep, that works like a charm.  Thanks a ton!!!  Rob

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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