Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a complete string representation of an object (like in the Immediate Window in Visual Studio)

Given the following example class:

public class MyClass
{
    public string S { get; set; }
    public int I { get; set; }
    public DateTime D { get; set; }
    private float F { get; set; }
    private long l;

    public MyClass()
    {
        S = "foo";
        I = 42;
        D = new DateTime(2011, 11, 11);
        F = 3.14f;
        l = 12435;
    }
}

If I in my application have an instance myClass of this class, step through the code in debug mode (Visual Studio 2010), and at some point types myClass into the Immediate Window, the following is displayed:

{MyClass}
    D: {11.11.2011 00:00:00}
    F: 3.14
    I: 42
    l: 12435
    S: "foo"

Getting such a string representation of the object and all its values could be very useful for logging purposes. Is there a nice and easy way to achieve this?

I guess the Immediate Window uses reflection to loop over all fields and properties, but I thought I'd ask just in case there already exists some utility function or anything to do it.

like image 914
Julian Avatar asked Jul 14 '11 14:07

Julian


People also ask

How do we get a string representation of an object?

The toString() method returns the string representation of an object. A default implementation of this method is included in the Object class. This implementation returns a string containing the name of the object's class and its hash code.

How do I get immediate window in Visual Studio?

On the Debug menu, choose Windows > Immediate.

Which function provide string representation of the object?

str() and repr() both are used to get a string representation of object.

What is a string representation?

A String is represented as objects in Java. Accordingly, an object contains values stored in instance variables within the object. An object also contains bodies of code that operate upon the object. These bodies of code are called methods.


1 Answers

This will store all fields in a dictionary (ensuring they can be read first):

public static Dictionary<string, object> GeneratePropertiesDictionary(object myClass)
{
    return myClass.GetType()
                  .GetProperties()
                  .Where(p => p.CanRead)
                  .ToDictionary(p => p.Name, p => p.GetValue(myClass, null));
}

You could easily modify this to append each name/value to a StringBuilder object instead of a dictionary though, and dump that to a file.

like image 130
Grant Winney Avatar answered Oct 23 '22 23:10

Grant Winney