Last active
August 29, 2015 14:27
-
-
Save prskr/3f5a36047036d421ac20 to your computer and use it in GitHub Desktop.
Extended ToString Method based on reflection
This file contains hidden or 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
| 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