Search code examples
vb.netpropertyinfo

Loop through values of properties of an object?


I know there are a bunch of topics with the same question, but I am just so confused.

I want to loop through my objects properties and write the value.

But everything I have seen says to

        Dim pinfo() As PropertyInfo = MyCompanies(1).GetType().GetProperties()

This creates an array with the info of the properties, but it does not store the actual value of that object.property,

enter image description here

The name of the property is ticker, but the value of Mycompanies(1).ticker is AMZN.

My Code:

 Dim pinfo() As PropertyInfo = MyCompanies(1).GetType().GetProperties()

 'Loop through Properties 
 For pi = 0 To pinfo.Length - 1
        'I want to get the values of each property
        Console.WriteLine(?)
    Next pi

Note: MyCompanies(1) is just the second object in an object array, all objects are of the company class

https://msdn.microsoft.com/en-us/library/b05d59ty(v=vs.110).aspx doesnt help either. It leads me to believe that I should do:

    For Each pi In pinfo
        'I want to get the values of each property
        Console.WriteLine(PropertyInfo.GetValue(MyCompanies(1))
    Next pi

but that wont even build. Is it because I am trying to give it the object by using the position in the array?

...and outside of this loop I will have to loop through my object array, so i figured i could just replace the 1 with an i...


Solution

  • You should be calling like this:

    Dim props As PropertyInfo() = MyCompanies(1).GetType().GetProperties()

    Note GetProperties returns an array of PropertyInfo - one representing each property.

    Then, to loop:

    For Each prop in props
        Console.WriteLine(prop.GetValue(MyCompanies(1)).ToString())
    Next
    

    Note that the PropertyInfo class does not contain a reference to the specific object from which you derived the type information (which is why you can't just call prop.GetValue()).

    It is simply a kind of template which describes the type in question - and therefore you have to pass it a reference to the actual object whose property value you want to be extracted.

    If you were accessing multiple MyCompanies objects, you would only derive the type information once, and you would then reuse it.

    For example:

    Dim props As PropertyInfo() = MyCompanies(1).GetType().GetProperties()
    
    For Each company in MyCompanies
    
        Console.WriteLine(company.ToString()) 'e.g. to print the company name
    
        For Each prop in props
            Console.WriteLine(prop.GetValue(company).ToString())
        Next
    Next
    

    I haven't tested the code so excuse any small slips.