9 december 2006

VB.NET looping through properties of a self defined object

I use the toString()-method mostly for debugging. So it would be usefull if there was a way to loop through all properties of a object. So I wrote this function: [code lang="VB.NET"] Public Overrides Function toString() As String Dim PropertyInfo As PropertyInfo() = Me.GetType().GetProperties() Dim PropertyItem As PropertyInfo Dim str As String = "" For Each PropertyItem In PropertyInfo str += PropertyItem.Name & ": " & _ Me.GetType().GetProperty(PropertyItem.Name).GetValue(Me, Nothing).ToString() & ", " Next Return str End Function [/code] It displays the name of the property and the value of that property. Why is this function usefull? Because you don't have to modificate the toString()-method each time you add a new property, the code is reusable and so on. Why did I post it on my blog? Because I spent a lot of time searching for something like this on google, msdn2, ... EDIT: don't forget to import System.Reflection [code lang="VB.NET"] Imports System.Reflection [/code]

Dit artikel gaat over: , , , . VB.NET looping through properties of a self defined object werd geschreven door Tijs.
Er zijn al 5 reacties.

Reacties

Kelly

Kelly schreef:
09/12/06

handig! =) *saves*

tys

tys schreef:
09/12/06

EDIT: don't forget to import System.Reflection

[code lang="VB.NET"]
Imports System.Reflection
[/code]

Mark

Mark schreef:
18/04/07

Thank You

JGO

JGO schreef:
06/11/07

Thank you for this! I spent a LOT of time looking for this exact functionality. Thanks again for taking the time to post it.

Eugene

Eugene schreef:
06/10/08

Darn, thanks m8. That was really valuable.

Reageer velden gemarkeerd met een sterretje zijn verplicht

*