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.
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.
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).
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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With