2

I have an extension method to get a property name as string:

    public static string GetPropertyName<T, TResult>(this T obj, Expression<Func<T, TResult>> propertyId)
    {
        return ((MemberExpression)propertyId.Body).Member.Name;
    }

Now I have another method, expecting to pass in list (param) of this kind of property lamba expression. I want this new method to reuse the 1st method, but can't figure out how to pass it over

    public string Test<T>(params Expression<Func<T, object>>[] ps)
    {
        foreach (var p in ps)
        {
                var howToCodeThis = p.GetPropertyName(dummy => dummy);

expected usage:

                var result = Test<Something>(request.Sorting
                , x => x.prop1
                , x => x.prop2
                , x => x.prop3
                );

Update: Backs answer worked once I change my GetPropertyName to cater for UnaryExpression:

    public static string GetPropertyName<T, TResult>(this T obj, Expression<Func<T, TResult>> propertyId)
    {
        if (propertyId.Body is MemberExpression)
            return ((MemberExpression)propertyId.Body).Member.Name;

        if (propertyId.Body is UnaryExpression)
        {
            var op = ((UnaryExpression)propertyId.Body).Operand;
            return ((MemberExpression)op).Member.Name;
        }

        throw new NotImplementedException(string.Format("GetPropertyName - {0}", propertyId.Body.GetType().FullName));
    }
Kelmen
  • 1,053
  • 1
  • 11
  • 24
  • I asked a very similar question not too long ago: http://stackoverflow.com/questions/30734899/passing-a-lambda-expression-as-parameter-to-a-method –  Nov 03 '15 at 10:33
  • 1
    i voted up your question. i really hate ppl simply downvote a question without reason. – Kelmen Nov 03 '15 at 11:50
  • thanks. Downvotes are helpful if there's an explanation, I agree with you. –  Nov 03 '15 at 12:39

1 Answers1

1
var howToCodeThis = GetPropertyName(default(T), p);

OR

var howToCodeThis = default(T).GetPropertyName(p);

But I noteced, you don't use obj in GetPropertyName method.

Backs
  • 24,430
  • 5
  • 58
  • 85
  • I think the reason `obj` is there is so that inferring type parameters works. – svick Nov 03 '15 at 11:30
  • that method is an extension, such is the way of the coding syntax. using it is as such myObj.GetPropertyName(x => x.Prop) – Kelmen Nov 03 '15 at 11:48
  • I can only use 2nd option, as the method is an extension method. it doesn't work, giving error: Unable to cast object of type 'System.Linq.Expressions.UnaryExpression' to type 'System.Linq.Expressions.MemberExpression – Kelmen Nov 04 '15 at 09:18
  • the issue is due to my GetPropertyName. I posted an update about this, and yours answer worked. – Kelmen Nov 04 '15 at 09:25