Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through each property of a custom vb.net object?

How can I go through each of the properties in my custom object? It is not a collection object, but is there something like this for non-collection objects?

For Each entry as String in myObject     ' Do stuff here... Next 

There are string, integer and boolean properties in my object.

like image 862
Anders Avatar asked Nov 24 '08 15:11

Anders


People also ask

Which loop will you use to iterate through properties of an object?

A for...in loop only iterates over enumerable, non-Symbol properties. Objects created from built–in constructors like Array and Object have inherited non–enumerable properties from Array.

Which method will you use to iterate the properties of an object in JS?

Object.keys() method was introduced in ES6 to make it easier to loop over objects. It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys).

Can we iterate an object?

There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.


2 Answers

By using reflection you can do that. In C# it looks like that;

PropertyInfo[] propertyInfo = myobject.GetType().GetProperties(); 

Added a VB.Net translation:

Dim info() As PropertyInfo = myobject.GetType().GetProperties() 
like image 184
Ali Ersöz Avatar answered Sep 23 '22 08:09

Ali Ersöz


You can use System.Reflection namespace to query information about the object type.

For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()    If p.CanRead Then        Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing))    End If Next 

Please note that it is not suggested to use this approach instead of collections in your code. Reflection is a performance intensive thing and should be used wisely.

like image 21
mmx Avatar answered Sep 22 '22 08:09

mmx