get properties of object c# code example

Example 1: c# get all class properties

//through reflection
using System.Reflection;

//Get a List of the properties from a type
public static PropertyInfo[] ListOfPropertiesFromInstance(Type AType)
{
  	if (InstanceOfAType == null) return null;
    return AType.GetProperties(BindingFlags.Public);
}

//Get a List of the properties from a instance of a class
public static PropertyInfo[] ListOfPropertiesFromInstance(object InstanceOfAType)
{
  	if (InstanceOfAType == null) return null;
  	Type TheType = InstanceOfAType.GetType();
    return TheType.GetProperties(BindingFlags.Public);
}

//purrfect for usage example and Get a Map of the properties from a instance of a class
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 property type of list

var obj = new PropClassDemo();
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
	if(prop.PropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(prop.PropertyType))
	{
		Console.Writeline("This prop's type is Ienumerable");
	}
}

//Note: string is an ienumerable too

Example 3: C# get object property name

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