Real World Scenario: Object Writer

Recently in a project I was facing a bug which was very difficult to reproduce. So, I decided to log object with complete properties in a text file. This code can be really useful for those who want to solve bugs which only occurs very rarely.

Here is the code of my class which converts object into a string:-

public class ObjectWriter
{
    public static string GetObjectString(object obj)
    {
        StringBuilder sb = new StringBuilder(1024);
        sb.Append("Type: ");
        sb.AppendLine(obj.GetType().ToString());
 
        if (obj == null)
        {
            sb.AppendLine("Value: Null");
        }
        else
        {
            sb.AppendLine("-------------------------");
            var type = obj.GetType();
 
            foreach (var prop in type.GetProperties())
            {
                var val = prop.GetValue(obj, new object[] { });
                var valStr = val == null ? "" : val.ToString();
                sb.AppendLine(prop.Name + ":" + valStr);
            }
        }
        return sb.ToString();
    }
}


Here is sample output and usage of my code:-


In above image I have called ObjectWriter.GetObjectString(ie) and in result varibale you can see that I can see its type and other fields information. You can write this information in log file for further investigation.