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?
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);
}
                        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