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.
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.
On the Debug menu, choose Windows > Immediate.
str() and repr() both are used to get a string representation of object.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With