For debugging purposes I need to print all public fields/properties of certain class instance. Can I do that automatically somehow? Probably there are new feature in .NET 4.0? For example WPF DataGrid can do something like that.
This can be do manualy refer to this question Iterate through class fields and print them but I’m interesting if I can do that using some library method, instead of coding myself?
I.e. I want to replace this code:
foreach (PropertyInfo prop in typeof(ServerInfo).GetProperties())
{
result += prop.Name + " = " + prop.GetValue(si, null) + "\n";
}
foreach (FieldInfo prop in typeof(ServerInfo).GetFields())
{
result += prop.Name + " = " + prop.GetValue(si) + "\n";
}
return result;
I’m not sure why you’re looking for better code. The code you have is just a few lines and looks fine to me.
If you want to modify the code that you have to work with any type, then that’s simple:
Another thing that could be made better in this code is efficiency: you should use
StringBuilderinstead of concatenating strings.