0
Func<T, TField> GetFunc<T, TField> (this FieldInfo fieldInfo) {
      var instanceParameter = Expression.Parameter (typeof (T), "instance");
      var fieldExpression = Expression.Field (instanceParameter, fieldInfo);
      var lambda = Expression.Lambda<Func<T, TField>> (fieldExpression, instanceParameter);
      return lambda.Compile ();
}

I wrote this method to get this lambda expression.

return (T instance) => instance.[fieldInfo.Name];

But how do I write the method to get this lambda expression?

return (T instance) => ref instance.[fieldInfo.Name];
7
  • stackoverflow.com/questions/8504598 Commented Oct 19, 2022 at 11:47
  • ... There is CS8155 compiler error so I don't think if it's possible (create expression with ref return) ... Commented Oct 19, 2022 at 11:59
  • 1
    ... but even with that, I suspect this is not possible. Expression trees are basically frozen in time from when they were introduced, and support for more recent C# features hasn't been added to them Commented Oct 19, 2022 at 12:21
  • 1
    also to extend on what @canton7 says (although IIRC some minor additions have been made): expression trees want to be able to work in fallback reflection mode for when the runtime doesn't allow IL-emit; and you can't work properly with ref values via reflection - hence I doubt it would be added Commented Oct 19, 2022 at 12:29
  • 1
    at that point you're just talking ILGenerator, and yes: ILGenerator can handle both managed and unmanaged pointers just fine Commented Oct 19, 2022 at 13:42

0

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.