Darxis Darxis - 3 months ago 22
C# Question

Convert Expression<Func<T1>> to Expression<Func<T1, T2>>

I have the following C# code, that gets the member name from lambda expression:

public static class ObjectInformation<T>
{
public static string GetPropertyName<TProp>(Expression<Func<T, TProp>> propertyLambda)
{
var memberExpression = propertyLambda.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("Lambda must return a property.");
}

return memberExpression.Member.Name;
}
}

public static class ObjectInformation
{
public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
var memberExpression = propertyLambda.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("Lambda must return a property.");
}

return memberExpression.Member.Name;
}
}


I call the methods like this:

ObjectInformation<RemoteCollectionContentViewModel>.GetPropertyName(e => e.SomeProperty);
ObjectInformation.GetPropertyName(() => SomeProperty)


I would like the second method to use the first one (not to duplicate the code), so I need to convert
Func<T>
to
Func<T, TProp>
. How could I achieve that?

Answer

There's no easy way to convert expression type. You'll have to rebuild the whole expression tree. It isn't worth the trouble. There's a good old way of extracting the common logic:

public static class ObjectInformation
{
    public static string GetPropertyName<T, TProp> (Expression<Func<T, TProp>> propertyLambda)
    {
        return GetPropertyName((LambdaExpression)propertyLambda);
    }

    public static string GetPropertyName<T> (Expression<Func<T>> propertyLambda)
    {
        return GetPropertyName((LambdaExpression)propertyLambda);
    }

    private static string GetPropertyName (LambdaExpression propertyLambda)
    {
        var memberExpression = propertyLambda.Body as MemberExpression;
        if (memberExpression == null)
            throw new ArgumentException("Lambda must return a property.");
        return memberExpression.Member.Name;
    }
}
Comments