Iterate through class properties

13,958

You want to use Reflection, which just means inspecting the types in an assembly. You can do this via the System.Reflection namespace.

See the following article on the msdn magazine for examples of reflection in VB.Net: http://msdn.microsoft.com/en-us/magazine/cc163750.aspx

An example of iterating over the members of a type in that article is as follows:

Dim t As Type = GetType(AcmeCorp.BusinessLogic.Customer)
For Each member As MemberInfo In t.GetMembers
  Console.WriteLine(member.Name)
Next
Share:
13,958
donL
Author by

donL

Updated on June 04, 2022

Comments

  • donL
    donL almost 2 years

    I have a VB.NET class called ticket that has several public properties of type 'field'. I would like to have a way that I can iterate through all of these properties (with a for each) and perform a specific task on each of them. I thought that maybe the best way was to create a list(Of field) and fill the list with the 'field' properties of that class. What I don't know how to do is get the properties into the list dynamically so that if I add properties in the future I don't have to type them into the list manually. Any thoughts on how I might do this? I tried searching for and found some examples of using reflection but I could only figure out how to get at the name of the property and not the property itself.

    Here is an example of a class:

    Public Class ticket
        Public Property location As New field
        Public Property user As New field
        Public Property callType As New field
        Public Property dateOfCall As New field
        Public Property tech As New field
        Public Property description As New field
    
        Public Property myFields As New List(Of field)
    
    'What if field had a property of value and I wanted to increment all of the fields    in this class by one
    
    Public Sub plusOne()
        For Each x As field In myFields()
            x.value += 1
        Next
    End Sub
    
    End Class