Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Reflection & Order of discovered properties

, 3 Oct 2012
Rate this:
Please Sign up or sign in to vote.
In .NET environement Reflection provides several methods to obtain information about any type from the type system. One of these methods is GetProperties method which retrieves a list of all the properties of a given type. This method returns an array of PropertyInfo objects. PropertyInfo[] propLis
In .NET environement Reflection provides several methods to obtain information about any type from the type system. One of these methods is GetProperties method which retrieves a list of all the properties of a given type. This method returns an array of PropertyInfo objects.
PropertyInfo[] propListInfo = type.GetProperties();
In most cases you don't care, but the order of the properties does not have to be the same if you run this method several times. This is well described in the documentation of this method. Microsoft also states, that your code should not be depending on the order of the properties obtained.

I had a very nice example of a bug resulting from the misuse of this method. A ObjectComparer class, which is dedicated to comparison of two objects of same type by recursively comparing it's properties, which I have inherited as legacy code on my current Silverlight project.

I have noticed, that the results of the comparison are not the same everytime I run the comparison. Concretely the first time the comparison was run on two same objects it always told me, that the objects are not equal. Take a look at the problematic code, which I have simplified a bit for this post:
private static bool CompareObjects(object initialObj, object currentObj, IList<String> filter)
{
 string returnMessage = string.Empty;

 Type type = initialObj.GetType();
 Type type2 = currentObj.GetType();

 PropertyInfo[] propListInfo = type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance).Where(x => !filter.Contains(x.Name)).ToArray();
 PropertyInfo[] propListInfo1 = type2.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance).Where(x => !filter.Contains(x.Name)).ToArray();

 //if class type is native i.e. string, int, boolean, etc.
 if (type.IsSealed == true && type.IsGenericType == false)
 {
  if (!initialObj.Equals(currentObj))
  {
   return false;
  }
 }
 else //class type is object
 {
  //loop through each property of object
  for (int count = 0; count < propListInfo.Length; count++){
   var result = CompareValues(propListInfo[count].GetValue(initialObj),propListInfo2[count].GetValue(currentObj));
   if(result == false) {
    return result;
   }
  }
 }
 return true;
}
So in order to correct this code, you will have to order both arrays by MetadataToken, which is a unique identifier of each property.
propListInfo = propListInfo.OrderBy(x=>x.MetadataToken).ToArray();
propListInfo1 = propListInfo1.OrderBy(x=>x.MetadataToken).ToArray();
There is some more information about how reflection works in this blog post.The issue is that the Reflection engine holds a "cache" for each type, in which it stocks the already "discovered" properties. The problem is that, this cache is cleared during garbage collection. When we ask for the properties, than they are served from the cache in the order in which they have been discovered.

However in my case, this information does not help. The issue occures only the first time that I ask the ObjectComparator to compare the objects and there is no reason that there should be any garbage collection between the first and second run...well no idea here. Sorting by MetadataToken has fixed the issue for me.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Jan Fajfr
Software Developer (Junior) OCTO Technology
Czech Republic Czech Republic
I work as IT consultant at OCTO Technology. Previously I have lived and studied CS in Prague, Paris and Valencia.
 
LinkedIn
Blog
GitHub
Articles at OCTO blog

Comments and Discussions

 
SuggestionI know it wasn't the point, but this could be more efficient PinmemberMatt T Heffron3-Oct-12 13:41 
GeneralRe: I know it wasn't the point, but this could be more efficient PinmemberJan Fajfr4-Oct-12 10:45 
GeneralRe: I know it wasn't the point, but this could be more efficient PinmemberMatt T Heffron4-Oct-12 11:24 
No, this is not currently used anywhere.
I just saw that your code could use some "cleanup", and I thought it might be fun! Wink | ;)
 
You can use it in the article.
 
It looks as if the CompareValues is really the same as CompareObjects without the filtering. (Unless it requires the values to be really the same Type.) Otherwise, this could call CompareObjects recursively with a null filter.
 
(I was wondering why you needed to compare objects that weren't the same Type...)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 3 Oct 2012
Article Copyright 2012 by Jan Fajfr
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid