Created
July 27, 2018 15:56
-
-
Save jetstreamin/9851a44830b84df290c3aee86aac91ee to your computer and use it in GitHub Desktop.
Object Dumper - C# way to dump all properties of an object
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
public static class ObjectDump | |
{ | |
public static void Write(TextWriter writer, object obj) | |
{ | |
if (obj == null) | |
{ | |
writer.WriteLine("Object is null"); | |
return; | |
} | |
writer.Write("Hash: "); | |
writer.WriteLine(obj.GetHashCode()); | |
writer.Write("Type: "); | |
writer.WriteLine(obj.GetType()); | |
var props = GetProperties(obj); | |
if (props.Count > 0) | |
{ | |
writer.WriteLine("-------------------------"); | |
} | |
foreach (var prop in props) | |
{ | |
writer.Write(prop.Key); | |
writer.Write(": "); | |
writer.WriteLine(prop.Value); | |
} | |
} | |
private static Dictionary<string, string> GetProperties(object obj) | |
{ | |
var props = new Dictionary<string, string>(); | |
if (obj == null) | |
return props; | |
var type = obj.GetType(); | |
foreach (var prop in type.GetProperties()) | |
{ | |
var val = prop.GetValue(obj, new object[] { }); | |
var valStr = val == null ? "" : val.ToString(); | |
props.Add(prop.Name, valStr); | |
} | |
return props; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment