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

x
  • 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
0
rbertke
Asked:
rbertke
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
        Get
            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"
                Else
                    p = p & "/Write"
                End If
            End If
            p = p & " Property " & pi.Name & "() of Type " & pi.PropertyType.ToString
            Debug.WriteLine(p)
        Next

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

End Class

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

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