I generally override the ToString() method to output the property names and the values associated to them. I got a bit tired of writing these by hand so I'm looking for a dynamic solution.
Main:
TestingClass tc = new TestingClass()
{
Prop1 = "blah1",
Prop2 = "blah2"
};
Console.WriteLine(tc.ToString());
Console.ReadLine();
TestingClass:
public class TestingClass
{
public string Prop1 { get; set; }//properties
public string Prop2 { get; set; }
public void Method1(string a) { }//method
public TestingClass() { }//const
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (Type type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
{
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
sb.Append(property.Name);
sb.Append(": ");
sb.Append(this.GetType().GetProperty(property.Name).Name);
sb.Append(System.Environment.NewLine);
}
}
return sb.ToString();
}
}
This currently outputs:
Prop1: System.String Prop1
Prop2: System.String Prop2
Desired Output:
Prop1: blah1
Prop2: blah2
I'm open for other solutions, it doesn't have to use reflection, it just has to produce the desired output.
This is what I found, that works with most compicated-types (including List):
usage:
Here is an extension which will report the standard types such as string, int and Datetime but will also report string lists (shown below in
AccessPoints
which the above answer could not handle). Note that the output is aligned such as:Below is the extension which takes in any type as long as its a class. It then reflects off of the public and private properties and if they are not null reports them.
Usage
myInstance.ReportAllProperties()
Note that this is based off my blog article C#: ToString To Report all Properties Even Private Ones Via Reflection which provides a more robust explanation of what is going on.
This works for me:
To make it available everywhere you can create an Extension.
It's not possible to override methods in an Extension, but still it should simplify your life.
You can then call
ToStringExtension()
on every object.Downside is, it doesn't work perfectly for lists etc., example:
I ran into this myself where I am looking for an option to serialize into something readable. If there are no read only properties xml serialization can give a readable string. However if there are read only properties / fields then xml serialization is not an option.