Last active
December 29, 2015 17:39
-
-
Save bojanbjelic/7705806 to your computer and use it in GitHub Desktop.
generic ToString method to show properties and values using Reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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