[RESOLVED] Looping through an Object
I have created a Consumer Object and I would like to loop through and display each property. So in my sample code I would like to have 2 message boxes displayed one with "ekim" another with "12987". But my object array, attributes, is always null. Is there a correct way to loop through an object?
public void Testing()
{
CConsumer Consumer = new CConsumer();
Consumer.FirstName = "ekim";
Consumer.LastName = "12987";
System.Reflection.MemberInfo inf = typeof(CConsumer);
object[] attributes;
attributes = inf.GetCustomAttributes(typeof(CConsumer), false);
foreach (Object attribute in attributes)
{
MessageBox.Show(attribute.ToString());
}
}
Thanks
Re: Looping through an Object
You would use PropertyInfo.
Code:
Type objType = Consumer.GetType();
PropertyInfo[] pi = objType.GetProperties();
foreach(PropertyInfo p in pi)
{
//Now, use p.
}
Re: Looping through an Object
Thanks for the response. To display the value just use GetValue
foreach (PropertyInfo p in pi)
{
MessageBox.Show(p.GetValue(Consumer, null).ToString());
}