I need to get all the properties using reflection in the order in which they are declared in the class. According to MSDN the order can not be guaranteed when using GetProperties()
The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order.
But I've read that there is a workaround by ordering the properties by the MetadataToken
. So my question is, is that safe? I cant seem find any information on MSDN about it. Or is there any other way of solving this problem?
My current implementation looks as follows:
var props = typeof(T)
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.OrderBy(x => x.MetadataToken);
Building on the above accepted solution, to get the exact Index you could use something like this
Given
Extensions
Usage
Note, there is no error checking or fault tolerance, you can add pepper and salt to taste
If you're going the attribute route, here's a method I've used in the past;
Then use it like this;
Where;
The method will barf if you run it on a type without comparable attributes on all of your properties obviously, so be careful how it's used and it should be sufficient for requirement.
I've left out the definition of Order : Attribute as there's a good sample in Yahia's link to Marc Gravell's post.