Order of properties from reflection change in .Net 2.0 by ThinqLinq

Order of properties from reflection change in .Net 2.0

Quick lesson: Don't rely on the order of the properties returned from reflection for processing.

Longer story:
On a recent project, I came up with a solution to report on items in an object structure by serializing the object to XML using a code based on reflection. Then in the report, I iterated through a series of XML nodes and used the XPathNavigator reading the nodes sequentially. In this scenario I needed an identifier code to be the first of each group of nodes. I found that .Net 1.1 would return the properties via reflection in the same order as they are contained within the class description, thus putting the ID property at the top of the class, I was fine and the module ran reasonably well.

When I upgraded the project to .Net 2.0, I found that the order returned by reflection is not the same as the order defined in the class definition. (I haven't determined what algorithm they used to determine the order returned by Type.GetProperties().) This caused the ID to no longer be the first node of each group and thus the report failed. I acknowledge that the original solution may have been flawed to have relied on the order of values returned by .GetProperties(), and have come up with a somewhat less elegant solution for the issue (kludge). I'm not insinuating that I dislike the changes in .Net, I was just caught off guard and want to let others know of this potential breaking change.

Posted on - Comment
comments powered by Disqus