public static string ToSortedString(this object value)
    BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
    SortedDictionary<string, string> values = new SortedDictionary<string, string>();

    PropertyInfo[] properties = value.GetType().GetProperties(bindingFlags);
    foreach (PropertyInfo property in properties)
        string propertyName = property.Name;
        object propertyValue = property.GetValue(value, null);
        string maskedValue = propertyValue == null ? "null" : propertyValue.ToString();

        values.Add(propertyName, maskedValue);

    StringBuilder sb = new StringBuilder();
    foreach (KeyValuePair<string, string> item in values)
        sb.AppendFormat("{0}={1}{2}", item.Key, item.Value, Environment.NewLine);

    return sb.ToString();
MyClass c = new MyClass();
string data = c.ToSortedString();


Returns an alphabetically sorted list for all public and instance properties, along with its associated values.


Double click on the code to select all.