A Simple Method to Get an Object's Properties and Values at Runtime
I recently wrote some code to integrate with a WCF service authored by a different team and encountered an error, happening internal to the service, during my initial integration testing of one of the methods. I wanted to provide the developer on the other team with the parameters I passed into the method when the exception occurred, and one of those parameters was an object with more than a few properties. To that end, I wrote a quick method to provide the object's properties and their values so I could include it in the exception handling on my end and provide this info to the other developer to aid in debugging.
This method requires a using statements for System.Reflection and System.Text. It could also be expanded a bit (for example, in the way it represents the value for property values that are objects), but as a quickly-written method it gets the job done.
This method requires a using statements for System.Reflection and System.Text. It could also be expanded a bit (for example, in the way it represents the value for property values that are objects), but as a quickly-written method it gets the job done.
protected string GetObjectPropertiesAndValues(object target) { StringBuilder output = new StringBuilder(); PropertyInfo[] props = target.GetType().GetProperties(); Type stringType = typeof(string); if (props != null) { foreach (var prop in props) { object propVal = prop.GetValue(target, null); if (propVal == null) output.Append( String.Format("{0} = (null)\n ", prop.Name)); else if (prop.PropertyType == stringType) output.Append( String.Format("{0} = \"{1}\"\n ", prop.Name, propVal)); else output.Append( String.Format("{0} = {1}\n ", prop.Name, propVal)); } } return output.ToString(); }
Comments
Post a Comment