Imagine a class with many public properties. For some reason, it is impossible to refactor this class into smaller subclasses.
I'd like to add a ToString override that returns something along the lines of:
Property 1: Value of property 1\n Property 2: Value of property 2\n ...
Is there a way to do this?
In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.
There you can type an object name (while in debug mode), press enter, and it is printed fairly prettily with all its stuff.
I think you can use a little reflection here. Take a look at Type.GetProperties()
.
public override string ToString() { return GetType().GetProperties() .Select(info => (info.Name, Value: info.GetValue(this, null) ?? "(null)")) .Aggregate( new StringBuilder(), (sb, pair) => sb.AppendLine($"{pair.Name}: {pair.Value}"), sb => sb.ToString()); }
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