Getting the field backing a property using Reflection 01 May 2009


Pluie, Pluie Update: the code has been moved to its own project page. Let's consider you're writing a LINQ provider. And that you need to opimize the following LINQ query:
from Person p in db where p.Age > 18 select p;
Let's add a constraint. The underlying storage engine stores data according to the field name. That would mean that when generating the query for the underlying storage system, you'll have to map
p.Age
into something that the underlying storage system will understand. In that case, a field. And all you have is a MemberExpression, giving you a PropertyInfo. The issue here is that you have no way to get the FieldInfo backing the property. If you think about it, it's normal. The setter and the getter of a property being traditional methods, they can contain any kind of code. Meaning that you can't always find a field backing the property. But in that case, it's ok, we're only interested in those forms of properties:
public int Age { get; set; }

private string name;

public string Name {
    get { return name; }
    set { name = value; }
}
Of course here what's interesting is how to actually get the field. I've used the Reflection based CIL reader I wrote about yesterday. I disassemble the body of either a getter or a setter of the property, and if it matches a simple IL pattern, that is, if it looks to be a property backed by a field, I simply return the field. To do the actual IL matching, I re-implemented something Rodrigo and I wrote when we were working on instrumenting assemblies at db4o. The code itself is pretty neat. Anyway, that's another opportunity to write a simple extension method:
public static FieldInfo GetBackingField (this PropertyInfo self)
Again, you're more than welcome to have a look at the implementation. Don't forget that it depends on the Reflection based CIL reader.