…meie igapäevast IT’d anna meile igapäev…

2010-08-25

.NET: reflection-based .ToString()

Filed under: Programmeerimine — Sander @ 10:58:49
Tags: , ,

Quite often, I need to see all or some the values of a class instance. In case of a single instance class, VS debugger itself will do the trick, but what if you have an array of class instances, say, mapped results from a database – and you need to see if the values are all there and correct? Going one by one through tens or hundreds of classes in Visual Studio debugger can be… cumbersome.

One way would be to write your own .ToString() override. But what if the class is complex, with dozens of fields or properties? It would mean a whole lot of work to add all of them to the result…

So, System.Reflection to the rescue! Remember that reflection is always more CPU-intensive, so use reflection-based .ToString() only during debugging – or, to be safe, wrap the code in #if DEBUG … #endif precompiler directives.

public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            Type type = GetType();
            sb.AppendLine(type.Name);
            foreach (FieldInfo info in type.GetFields())
                sb.AppendLine(string.Format("{0}: {1}", info.Name, info.GetValue(this)));

            foreach (PropertyInfo info in type.GetProperties())
                sb.AppendLine(string.Format("{0}: {1}", info.Name, info.GetValue(this, null)));

            return sb.ToString();
        }

Lisa kommentaar »

Kommentaare veel pole.

RSS feed for comments on this post. TrackBack URI

Lisa kommentaar

Create a free website or blog at WordPress.com.