Getting ALL the properties of an object
Another approach you can use in this situation is converting an object into a JSON object. The JSON.NET library makes this easy and almost any object can be represented in JSON. You can then loop through the objects properties as Name / Value pairs. This approach would be useful for composite objects which contain other objects as you can loop through them in a tree-like nature.
MyClass some_object = new MyClass() { PropA = "A", PropB = "B", PropC = "C" };
JObject json = JObject.FromObject(some_object);
foreach (JProperty property in json.Properties())
Console.WriteLine(property.Name + " - " + property.Value);
Console.ReadLine();
using System.Reflection; // reflection namespace
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{ return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
Console.WriteLine(propertyInfo.Name);
}
Source: http://www.csharp-examples.net/reflection-property-names/
You can use reflection.
// Get property array
var properties = GetProperties(some_object);
foreach (var p in properties)
{
string name = p.Name;
var value = p.GetValue(some_object, null);
}
private static PropertyInfo[] GetProperties(object obj)
{
return obj.GetType().GetProperties();
}
However, this still does not solve the problem where you have an object with 1000 properties.