Search This Blog

Wednesday, August 26, 2015

Ease debugging by serializing your objects

When you have a bunch of types containing an additional bunch of fields, it can be useful to be able to see all the values of a given object all at once, while debugging. Something that looks like:


In other words, I would like my types to be able to display all their properties in a stringified fashion (much like an object serialization). To accomplish this, I thought I could create a base class that overrides the ToString() method, and have all those classes inheriting from it - and sharing this same ToString() implementation. The same can be accomplished by adding an extension method to the object type, but the drawback would be I would have to cope with such method popping-up every time when intellisensing every object...

The snippet below illustrates how the discussed above can be achieved. The following will help only with primitive types. If your type has lists, for instance, you will need to add logic in how to treat it.

internal class Program
{
    private static void Main(string[] args)
    {
        public B()
        {
            b1 = "hello";
            b2 = "world";
        }
        B b = new B();
        Console.WriteLine(b.ToString());
        //prints hello,world
    }
}

public class A
{
    public override string ToString()
    {
        List<PropertyInfo> p = this.GetType().GetProperties().ToList();
        return string.Format(string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator, p.Select(z => z.GetValue(this))));
    }
}

public class B : A
{
    public string b1 { get; set; }
    public string b2 { get; set; }
}

No comments:

Post a Comment