Let’s say you have a poco and you want to list all its properties whith their values for debug purpose (or other purposes : logs, …)
You can write something like this :
string porperties = "property1 : " + this.property1; porperties+="property : " + this.property2; // .. porperties+="propertyn : " + this.propertyn;
but it’s long and painful, plus you can forget some properties
The reflection can help us here :
string porperties = ""; foreach (System.Reflection.PropertyInfo f in this.GetType().GetProperties()) { porperties += f.Name + " : " + f.GetValue(this, null) + Environment.NewLine; }
And if you want to be a bit clever, you create a base object and redefine the ‘ToString() method like this:
public class POCOBase { public override string ToString() { string ret = ""; foreach (System.Reflection.PropertyInfo f in this.GetType().GetProperties()) { ret += f.Name + " : " + f.GetValue(this, null) + Environment.NewLine; } return ret; } }
Then just inherit from POCOBase and call the ToString() method
The output should be something like this :
AccountID : 10 ExternalREF : 090xfe FIRSTNAME : USER 1 LASTNAME : TEST PHONE : 00044440000 RegisterDate : 30/09/2009 16:20:02 Remark :
I think it’s quick, easy and useful