In this entry, I will explain quickly how to get object properties using reflection and how to keep this list of properties always in the same order.
Using reflection it’s possible to get a C# object properties like this:
PropertyInfo[] properties = type.GetProperties();
Using this ‘GetProperties’ method, we are not sure to always have the same order. According to Microsoft help :
“The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.”
We can sort our array by alphabetic order etc… but if you want to keep the declaration order, the solution is in the use of the Metadata Token:
PropertyInfo[] properties = type.GetProperties();
Array.Sort(properties, new DeclarationOrderComparator());
And with the comparator:
{
int IComparer.Compare(Object x, Object y)
{
PropertyInfo first = x as PropertyInfo;
PropertyInfo second = y as PropertyInfo;
if (first.MetadataToken < second.MetadataToken)
return -1;
else if (first.MetadataToken > second.MetadataToken)
return 1;
return 0;
}
}
