Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically display all properties of a class and their values in a string? [duplicate]

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?

like image 671
mafu Avatar asked Oct 26 '10 12:10

mafu


People also ask

How do I copy values from one object to another in C#?

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.

Can we print object in C#?

There you can type an object name (while in debug mode), press enter, and it is printed fairly prettily with all its stuff.


1 Answers

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()); } 
like image 99
Oliver Avatar answered Sep 19 '22 10:09

Oliver