c# get all property names from object code example
Example 1: c# get all class properties
using System.Reflection;
public static PropertyInfo[] ListOfPropertiesFromInstance(Type AType)
{
if (InstanceOfAType == null) return null;
return AType.GetProperties(BindingFlags.Public);
}
public static PropertyInfo[] ListOfPropertiesFromInstance(object InstanceOfAType)
{
if (InstanceOfAType == null) return null;
Type TheType = InstanceOfAType.GetType();
return TheType.GetProperties(BindingFlags.Public);
}
public static Dictionary<string, object> DictionaryOfPropertiesFromInstance(object InstanceOfAType)
{
if (InstanceOfAType == null) return null;
Type TheType = InstanceOfAType.GetType();
PropertyInfo[] Properties = TheType.GetProperties(BindingFlags.Public);
Dictionary<string, PropertyInfo> PropertiesMap = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo Prop in Properties)
{
PropertiesMap.Add(Prop.Name, Prop);
}
return PropertiesMap;
}
Example 2: C# get object property name
using System.Reflection;
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
BindingFlags.Static);
Array.Sort(propertyInfos,
delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{ return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
foreach (PropertyInfo propertyInfo in propertyInfos)
{
Console.WriteLine(propertyInfo.Name);
}