Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net list class properties with values

I have a class, and I want to do a custom 'toString' function;

Public Class Person
    public property Name as string
    public property Age as interger

    public Overrides Function ToString() as string
         dim BigStr as string = ""
         for each Member as MemberInfo in Me.GetType.GetMembers
               bigst += Member.Name & " " & [thevalue of this instance]
         next
         return BigStr
    end function
end class

I want it to automatically display all properties with the value of the current instance. But I don't know how to get the value of property without specifically type it out. Is there a dynamic way?

like image 311
Dennis Avatar asked Apr 25 '26 12:04

Dennis


1 Answers

Type.GetMembers returns a list of MemberInfo objects, one per member of the type. However, not all members have values. Fields and properties have values, so if you get the list of just the fields or just the properties, you can ask them for their values. But things like methods don't have a value. You may be able to invoke them and read their return values, but that's different from reading the value of a property or a field.

In other words, you have to work differently with each member, depending on what kind of member it is. Since MemberInfo is the lowest common-denominator, it doesn't have any of the functionality which only works on some of the members. If you want the additional functionality available to you, you'll need to use one of the more specific methods like GetProperties or GetFields.

Since your class contains properties, you probably want to get the list of properties:

Public Class Person
    Public Property Name As String
    Public Property Age As Integer

    Public Overrides Function ToString() As String
        Dim bigStr As String = ""
        For Each p As PropertyInfo In Me.GetType().GetProperties()
            bigStr &= p.Name & " " & p.GetValue(Me)?.ToString()
        Next
        Return bigStr
    End Function
End Class
like image 115
Steven Doggart Avatar answered Apr 28 '26 06:04

Steven Doggart