During development, sometimes you need to know the state of an object and what data it contains. Debug is not always suitable approach, sometimes it is more convenient to view the state of an object on a web page or there may be a need to save information, for example, to a file.
There are many solutions to implement this task, and one of the simple and effective is to write an Extension
:
public static class Extensions
{
public static string ObjectProperties(this object obj)
{
var properties = obj.GetType().GetProperties();
var dump = new StringBuilder();
foreach (var prop in properties)
{
dump.AppendLine($"{prop.Name}: {prop.GetValue(obj, null)}");
}
return dump.ToString();
}
}
The option for obtaining a list of properties:
public static class Extensions
{
public static IList<string> ObjectPropertiesList(this object obj)
{
var properties = obj.GetType().GetProperties();
return properties.Select(prop => $"{prop.Name}: {prop.GetValue(obj, null)}").ToList();
}
}
This is a working solution, but it does not show the properties of nested objects. In this task, there is no need to show data at multiple nesting levels, it is enough to know about the first level.
public static IEnumerable<string> ObjectPropertiesFull(this object obj)
{
var dump = new List<string>();
var properties = obj.GetType().GetProperties();
foreach (var prop in properties)
{
if (prop.GetValue(obj, null) is ICollection collectionItems)
{
dump.Add(prop.Name);
foreach (var item in collectionItems)
{
dump.Add($" - {item}");
var objectType = item.GetType();
foreach (var nestedObjectProp in objectType.GetProperties())
{
dump.Add($" --- {nestedObjectProp.Name}: {nestedObjectProp.GetValue(item)}");
}
}
}
else if (prop.GetValue(obj, null) is Object nestedObject)
{
dump.Add($"{prop.Name}: {prop.GetValue(obj, null)}");
var nestedType = nestedObject.GetType();
foreach (var nestedTypeProp in nestedType.GetProperties())
{
dump.Add($" --- {nestedTypeProp.Name}: {nestedTypeProp.GetValue(nestedObject)}");
}
}
}
return dump;
}
This is sufficient in most cases. If there is a need to find out more information about an object, you can use recursion and a deeper analysis of the properties.
Codebase: https://codebase.blackball.lv/project/code-buns/source?file=Extensions/ObjectExtensions.cs#code-buns
