Jul 10, 2008

Display all the properties in an Object

I've come across this problem before, sometimes when working with classes designed by different groups, other times when I'm being lazy & don't want to look through my code. Either way, it's sometimes handy to be able to iterate through the properties of an object. So, here's a "quickie" to dump the property names/values to an exception.

Definition:
public void showObjProperties( object myObject ) {
System.ComponentModel.PropertyDescriptorCollection objProperties = System.ComponentModel.TypeDescriptor.GetProperties( myObject );
string strTmp = "";
string strType = myObject.GetType( ).ToString( );
for ( int i = 0; i < objProperties.Count; i++ ) {
strTmp += strType + "." + objProperties[i].Name + Environment.NewLine;
//strTmp += strType + "." + objProperties[i].Name + ": " + objProperties[i].GetValue( myObject ).ToString( ) + Environment.NewLine;
}
throw new Exception( "Props: " + Environment.NewLine + strTmp );
}


Calling code:
String[] aryString = new String[] { "test1", "test2", "test3" };
showObjProperties( aryString );


Results:
Props: 
System.String[].Length
System.String[].SyncRoot
System.String[].Rank
System.String[].IsReadOnly
System.String[].IsFixedSize
System.String[].IsSynchronized
System.String[].LongLength

2 comments:

Fit_Office_Chick said...

Thank you, dude, this was VERY useful.

IanCaz said...

Glad I could help.