Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the fields of a struct?

I created a struct:

public struct User {
   public string name;
   public string email;
   public string age;
}

Then create one:

 User user = new User();
 user.name = "Freewind";
 user.email = "[email protected]";
 user.age = 100;

Then display it:

MessageBox.Show(user.ToString());

I hope it can print all of the fields of the user struct, but it's not. It just shows:

MyApp.User

Is there a easy way to display all the fields of a struct?

like image 773
Freewind Avatar asked Dec 26 '22 20:12

Freewind


1 Answers

Override the ToString method on your struct:

public override string ToString()
{
    return String.Format("name={0}, email={1}, age={2}", this.name, this.email, this.age);
}

Note that this is not automatic and you will have to manually add any fields/properties to the string.

With reflection you can do something like this:

public override string ToString()
{
    Type type = this.GetType();
    FieldInfo[] fields = type.GetFields();
    PropertyInfo[] properties = type.GetProperties();
    User user = this;

    Dictionary<string, object> values = new Dictionary<string, object>();
    Array.ForEach(fields, (field) => values.Add(field.Name, field.GetValue(user)));
    Array.ForEach(properties, (property) =>
        {
            if (property.CanRead)
                values.Add(property.Name, property.GetValue(user, null));
        });

    return String.Join(", ", values);
}
like image 118
SomeWritesReserved Avatar answered Dec 31 '22 13:12

SomeWritesReserved