Skip to content

Instantly share code, notes, and snippets.

@derekgates
Created January 7, 2014 19:47
Show Gist options
  • Save derekgates/8305602 to your computer and use it in GitHub Desktop.
Save derekgates/8305602 to your computer and use it in GitHub Desktop.
PrintPublicPropertiesAndFields() makes a clean string representation of a class with it's properties and fields.
/// <summary>
/// Returns a string containing all of the public properties and fields for a given type.
/// </summary>
/// <param name="o">Type to print properties and fields for.</param>
/// <returns>Properties and fields seperated by newlines.</returns>
public static string PrintPublicPropertiesAndFields(this object o, string seperator = "\r\n")
{
StringBuilder sb = new StringBuilder();
Type otype = o.GetType();
foreach (PropertyInfo p in otype.GetProperties())
if (p.CanRead)
sb.Append((sb.Length != 0 ? seperator : "") + string.Format("{0}: {1}", p.Name, p.GetValue(o, null)));
foreach (FieldInfo fi in otype.GetFields())
sb.Append((sb.Length != 0 ? seperator : "") + string.Format("{0}: {1}", fi.Name, fi.GetValue(o)));
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment