Skip to content

Instantly share code, notes, and snippets.

@bojanbjelic
Last active December 29, 2015 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bojanbjelic/7705806 to your computer and use it in GitHub Desktop.
Save bojanbjelic/7705806 to your computer and use it in GitHub Desktop.
generic ToString method to show properties and values using Reflection
public override string ToString()
{
var propertiesInfo =
GetType().GetProperties().Where(p => Attribute.IsDefined(p, typeof (DataMemberAttribute)));
StringBuilder str = new StringBuilder();
foreach (var propertyInfo in propertiesInfo)
{
if (str.Length > 0)
str.Append(", ");
string enclosing = propertyInfo.PropertyType == typeof (string) ||
propertyInfo.PropertyType == typeof (char)
? "\""
: "";
str.AppendFormat("{0} : {2}{1}{2}", propertyInfo.Name, propertyInfo.GetValue(this, null), enclosing);
}
return str.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment