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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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()
Method 2
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.
Method 3
System.Reflection is “heavy-weight”, i always implement a lighter method first..
//C#
if (item is IEnumerable) {
foreach (object o in item as IEnumerable) {
//do function
}
} else {
foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties()) {
if (p.CanRead) {
Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, null)); //possible function
}
}
}
‘VB.Net
If TypeOf item Is IEnumerable Then
For Each o As Object In TryCast(item, IEnumerable)
'Do Function
Next
Else
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)) 'possible function
End If
Next
End If
Method 4
You can use reflection… With Reflection you can examine every member of a class (a Type), proeprties, methods, contructors, fields, etc..
using System.Reflection;
Type type = job.GetType();
foreach ( MemberInfo memInfo in type.GetMembers() )
if (memInfo is PropertyInfo)
{
// Do Something
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0