Skip to content

Instantly share code, notes, and snippets.

@elranu
Created January 31, 2017 22:27
Show Gist options
  • Save elranu/b186dec880d6be0ad814ff7d52cd5e64 to your computer and use it in GitHub Desktop.
Save elranu/b186dec880d6be0ad814ff7d52cd5e64 to your computer and use it in GitHub Desktop.
C# object to string. To write an object in a readble format
public static class ReflectionExtensions
{
/// <summary>
/// Turns into string all the properties of an object.
/// The idea of this method is to make an object more readable. The idea of this method is to be typically used in logs, to know the full status of an object.
/// </summary>
/// <param name="obj">Object to get the properties of</param>
/// <param name="tab">The tab to print the object</param>
/// <returns>Object properties in readable string format</returns>
public static string PropertiesToString(this object obj, int tab = 0)
{
if (obj == null) return "object is null";
var type = obj.GetType();
var properties = type.GetProperties().Where(x => !IsEnumerable(x.PropertyType)); // none IEnumerables first so is more readable
properties = properties.Concat(type.GetProperties().Where(x => IsEnumerable(x.PropertyType)));
var tabs = string.Empty;
for (int i = 0; i < tab; i++)
{
tabs +="\t ";
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat(tabs + "Object of type '{0}' has the following properties: ", type.Name);
sb.AppendLine();
foreach (var prop in properties)
{
var value = prop.GetValue(obj, null) ?? "(null)";
var enumerable = (value is string) ? null : value as IEnumerable; // strings are consider IEnumerable of chars.
if (enumerable != null)
{
sb.Append(tabs + "# "+ prop.Name + ": ");
sb.AppendLine("");
foreach (var item in enumerable)
{
sb.Append(PropertiesToString(item, tab + 1));
}
}
else
{
sb.Append(tabs + "- "+ prop.Name + ": ");
sb.AppendLine(ConvertEx.ChangeType<string>(value));
}
}
return sb.ToString();
}
private static bool IsEnumerable(Type ty)
{
var ret = typeof(string).IsAssignableFrom(ty);
if (ret) return false;
return typeof(IEnumerable).IsAssignableFrom(ty);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment