Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic override of ToString() using Reflection

I generally override the ToString() method to output the property names and the values associated to them. I got a bit tired of writing these by hand so I'm looking for a dynamic solution.

Main:

TestingClass tc = new TestingClass()
{
    Prop1 = "blah1",
    Prop2 = "blah2"
};
Console.WriteLine(tc.ToString());
Console.ReadLine();

TestingClass:

public class TestingClass
{
    public string Prop1 { get; set; }//properties
    public string Prop2 { get; set; }
    public void Method1(string a) { }//method
    public TestingClass() { }//const
    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (Type type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
        {
            foreach (System.Reflection.PropertyInfo property in type.GetProperties())
            {
                sb.Append(property.Name);
                sb.Append(": ");
                sb.Append(this.GetType().GetProperty(property.Name).Name);
                sb.Append(System.Environment.NewLine);
            }
        }
        return sb.ToString();
    }
}

This currently outputs:

Prop1: System.String Prop1
Prop2: System.String Prop2

Desired Output:

Prop1: blah1
Prop2: blah2

I'm open for other solutions, it doesn't have to use reflection, it just has to produce the desired output.

like image 554
bizah Avatar asked Feb 15 '12 18:02

bizah


1 Answers

I would use JSON, Serializer will do all the hard work for you:

    public static class ObjectExtensions
    {
        public static string ToStringEx(this object obj)
        {
            return JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true });
        }
    }
like image 73
jiri Avatar answered Sep 23 '22 21:09

jiri