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);
On .net 4.5 (and even .net 4.0 in vs2012) you can do much better with reflection using clever trick with
[CallerLineNumber]
attribute, letting compiler insert order into your properties for you:And then use reflection:
If you have to deal with partial classes, you can additionaly sort the properties using
[CallerFilePath]
.