Darxis
Darxis

Reputation: 1570

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?

Upvotes: 2

Views: 308

Answers (1)

Athari
Athari

Reputation: 34275

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;
    }
}

Upvotes: 4

Related Questions