Skip to content

Instantly share code, notes, and snippets.

@prskr
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save prskr/3f5a36047036d421ac20 to your computer and use it in GitHub Desktop.

Select an option

Save prskr/3f5a36047036d421ac20 to your computer and use it in GitHub Desktop.
Extended ToString Method based on reflection
using System.Linq;
using System.Text;
namespace TicketSystemTests
{
public static class ToStringExtension
{
public static string ToStringReflected(this object obj)
{
var valuesDict =
obj.GetType()
.GetProperties()
.ToDictionary(propertyInfo => propertyInfo.Name,
propertyInfo =>
propertyInfo.GetValue(obj) != null ? propertyInfo.GetValue(obj).ToString() : string.Empty);
var sb = new StringBuilder();
foreach (var entry in valuesDict)
{
//C# 6.0 version
//sb.Append($"{entry.Key}: {entry.Value}");
//regular string format version
sb.AppendFormat("{0}: {1}\n", entry.Key, entry.Value);
}
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment