2

This is what I am trying to accomplish:

public static Expression<Func<object, object>>[] Expressions() 
    => new Expression<Func<object, object>>[]
        {
            (Type1 t1) => t1.t1Field,
            (Type2 t2) => t2.t2Field,
            ...
            (TypeN tN) => tN.tNField
        };

The compiler does not like the Type[i] part: Cannot convert lambda expression to delegate type 'Expression<Func<object, object>>' because the parameter types do not match the delegate parameter.

I have tried using dynamic instead of object, but it didn't work.

I have also tried to achieve something like this, without success:

public static Expression<Func<object, object>> Cast<T>(Expression<Func<T, object>> expression)
2
  • Can´t you just uise a list of Delegate? Relying on the statically typed Func<T, T1, ...> assumes you know those types at compile-time. What you seem to want is providing the corect types at runtime. Apart from this even if you could store different expressions into a single list, how would you compile them and call the appropriate delegate? They´re just of type Func<object, object> which would allow to pass an instance of Type2 to the first element as well. Commented Feb 13, 2019 at 13:19
  • @HimBromBeere The final goal is to later extract the property name as a string, via memberExpr.ToString(). I am not experienced enough to know if this could work with delegates. Commented Feb 13, 2019 at 13:44

1 Answer 1

1

Your return type is an array of lambdas that accept object and return object. But you return an array of lambdas each of them accept some user type. So simplest way to make it work is to add type cast:

public static Expression<Func<object, object>>[] Expressions()
  => new Expression<Func<object, object>>[]
  {
      (Object o) => ((Type1)o).t1Field,
      (Object o) => ((Type2)o).t2Field,
  };
Sign up to request clarification or add additional context in comments.

2 Comments

This is perfect, I didn't think of this solution! Thanks. It can be even simplified to (o) => ((Type1)o).t1Field, the first object is inferred from the array declaration.
This approach is dangerous if you call one of those delegates, e.g. expressions[0].Compile()(instanceOfType2); which will cause an InvalidCastException. So you don´t get any typ-safety by using aFunc<object, object>. That´s why I added my comment above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.