Just Code‎ > ‎

C# - Print all fields, in a class, and their values. Excelent ToString()

posted Feb 14, 2010, 3:42 AM by Peter Henell   [ updated Feb 15, 2010, 4:40 AM ]
public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\n\t\t\t\t");
            foreach (FieldInfo field in this.GetType().GetFields(
                BindingFlags.Instance | BindingFlags.NonPublic))
            {
                object val = field.GetValue(this);
                if (val == null)
                {
                    sb.AppendFormat("{0} is null\n\t\t\t\t", field.Name);
                }
                else
                {
                    sb.AppendFormat("{0} ({1}) = {2}\n\t\t\t\t",
                        field.Name, val.GetType().Name, val);
                }
            }
            return sb.ToString();
        }
Comments