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


.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();
            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

Täida nõutavad väljad või kliki ikoonile, et sisse logida:

WordPress.com Logo

Sa kommenteerid kasutades oma WordPress.com kontot. Logi välja /  Muuda )

Google+ photo

Sa kommenteerid kasutades oma Google+ kontot. Logi välja /  Muuda )

Twitter picture

Sa kommenteerid kasutades oma Twitter kontot. Logi välja /  Muuda )

Facebook photo

Sa kommenteerid kasutades oma Facebook kontot. Logi välja /  Muuda )


Connecting to %s

Create a free website or blog at WordPress.com.