GetMemberInfo not found when using .NET 4.5.2

524 Views Asked by At

I was using this code in a library project using the Framework .NET 4.5 and it works fine

protected void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
{
    if (this.IsInpcActive)
    {
        this.OnPropertyChanged(property.GetMemberInfo().Name);
    }
}

I copy-pasted this code in a project using the .NET Frameworkwith 4.5.2 and I receive this error message:

'System.Linq.Expressions.Expression<System.Func<TProperty>>' does not contain a definition for 'GetMemberInfo' and no extension method 'GetMemberInfo' accepting a first argument of type 'System.Linq.Expressions.Expression<System.Func<TProperty>>' could be found (are you missing a using directive or an assembly reference?

As I don't really want to loose too much time, I found a plan B: extension method:

internal static class ExpressionExtensions
{
    #region Methods

    public static MemberInfo GetMemberInfo(this Expression expression)
    {
        var lambda = (LambdaExpression)expression;

        MemberExpression memberExpression;
        if (lambda.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)lambda.Body;
            memberExpression = (MemberExpression)unaryExpression.Operand;
        }
        else
            memberExpression = (MemberExpression)lambda.Body;

        return memberExpression.Member;
    }

    #endregion Methods
}

But I'm cusious: where did this method go?

1

There are 1 best solutions below

1
On BEST ANSWER

The Expression<TDelegate> class has no method GetMemberInfo(), and it never had. So your problem seems to lie here:

I copy-pasted this code in a project

So to me it looks like your version compiled against 4.5 used the same or an equivalent extension method, otherwise it wouldn't have compiled.

See for example this one from the Enterprise Library:

StaticReflection.GetMemberInfo<T, TProperty> Method

Retrieves a PropertyInfo object for the set method from an expression in the form x => x.SomeProperty.

So your original code should have this at the top:

using Microsoft.Practices.EnterpriseLibrary.Common.Utility;

And a reference to the Enterprise Library.