How to loop through all the properties of a class?
Use Reflection:
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list
Edit: You can also specify a BindingFlags value to type.GetProperties()
:
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).
You don't need to specify BindingFlags.GetProperty
, you use that when calling type.InvokeMember()
to get the value of a property.
Note that if the object you are talking about has a custom property model (such as DataRowView
etc for DataTable
), then you need to use TypeDescriptor
; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):
foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}
This also provides easy access to things like TypeConverter
for formatting:
string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));
VB version of C# given by Brannon:
Public Sub DisplayAll(ByVal Someobject As Foo)
Dim _type As Type = Someobject.GetType()
Dim properties() As PropertyInfo = _type.GetProperties() 'line 3
For Each _property As PropertyInfo In properties
Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing))
Next
End Sub
Using Binding flags in instead of line no.3
Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance
Dim properties() As PropertyInfo = _type.GetProperties(flags)