Skip to content

Instantly share code, notes, and snippets.

@sean-m
Last active November 2, 2023 22:45
Show Gist options
  • Save sean-m/07a973c8c4e04c2f12b7be0b1a48d40d to your computer and use it in GitHub Desktop.
Save sean-m/07a973c8c4e04c2f12b7be0b1a48d40d to your computer and use it in GitHub Desktop.
Takes an object and does a naive pass at turing it into a string that would print well in a console.
public string ToKvText(object entry) {
if (entry == null) return string.Empty;
StringBuilder sb = new StringBuilder();
var properties = entry.GetType().GetProperties();
var longestPropertyLength = properties.Select(x => x.Name.Length).Max();
int indentation = longestPropertyLength + 3;
foreach (var p in properties) {
sb.Append(p.Name.PadRight(longestPropertyLength));
sb.Append(" : ");
bool multiLine = false;
foreach (var value in (p.GetValue(entry) ?? "NULL").ToString().Split("\n")) {
var strValue = value ?? "NULL";
if (multiLine) {
sb.AppendLine((strValue).PadLeft(indentation + strValue.Length));
} else {
sb.AppendLine((strValue).PadRight(longestPropertyLength));
multiLine = true;
}
}
}
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment