Below I have setup an extension method that takes any object, cycles through its properties, and prints each out to a Console window in the format Name: Value
.
Specification / Scope:
- Handle only single objects (no collections)
code
public static string PropertiesToString<T>(this T obj, int tabs = 0) where T : class
{
int initTabs = tabs;
string result = string.Empty;
PropertyInfo[] propertyInfo = obj.GetType().GetProperties();
foreach (PropertyInfo property in propertyInfo)
{
string name = property.Name;
object value = property.GetValue(obj, null);
Type valueType = value.GetType();
if (valueType.IsValueType || valueType.Name.Equals("String"))
{
for (int i = 0; i < tabs; i++)
{
result += " ";
}
result += string.Format("{0}: {1}\n", name, value == null ? string.Empty : value.ToString());
}
else
{
result += string.Format("{0}:\n", name);
result += value.PropertiesToString(++tabs);
}
tabs = initTabs;
}
return result;
}
Here is a class I'm using to test this code, along with the lines responsible for creating an instance of the class and writing its properties to the Console:
Class:
public class Circle : IShape
{
public Circle(double x, double y, double radius)
{
Center = new Point
{
X = x,
Y = y
};
Radius = radius;
}
public Point Center { get; set; }
public double Radius { get; set; }
public double Area(int precision = 2)
{
return Math.Round(Radius * Radius * Math.PI, precision);
}
}
Main:
public static void Main(string[] args)
{
IShape circle = new Circle(5, 5, 10);
Console.WriteLine(circle.PropertiesToString());
Console.ReadLine();
}
The above method will also cycle through nested objects and print those to the Console as well, adding in tabs for readability's sake.
I'm kind of unfamiliar with System.Reflection
and was wondering if there was a more efficient way I could approach doing something like this.
string.Empty
toresult
ifvalue == null
. Otherwise I was only considering using this method for single objects, not collections. \$\endgroup\$