Expression Tree with Property Inheritance causes an argument exception

Posted by Adam Driscoll on Stack Overflow See other posts from Stack Overflow or by Adam Driscoll
Published on 2010-03-22T22:35:26Z Indexed on 2010/03/23 0:51 UTC
Read the original article Hit count: 380

Filed under:
|
|

Following this post: link text I'm trying to create an expression tree that references the property of a property. My code looks like this:

public interface IFoo
{
    void X {get;set;}
}

public interface IBar : IFoo
{
    void Y {get;set;}
}

public interface IFooBarContainer
{
    IBar Bar {get;set;}
}

public class Filterer
{
     //Where T = "IFooBarContainer"
     public IQueryable<T> Filter<T>(IEnumerable<T> collection)
     {
              var argument = Expression.Parameter(typeof (T), "item");

              //...

               //where propertyName = "IBar.X";
               PropertyOfProperty(argument, propertyName); 
     }

        private static MemberExpression PropertyOfProperty(Expression expr, string propertyName)
        {
            return propertyName.Split('.').Aggregate<string, MemberExpression>(null, (current, property) => Expression.Property(current ?? expr, property));
        }
}

I receive the exception:

System.ArgumentException: Instance property 'X' is not defined for type 'IBar'

ReSharper turned the code in the link above into the condensed statement in my example. Both forms of the method returned the same error.

If I reference IBar.Y the method does not fail.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about LINQ