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];
uchifune
  • 11
  • 2
  • https://stackoverflow.com/questions/8504598 – Robert Harvey Oct 19 '22 at 11:47
  • ... There is CS8155 compiler error so I don't think if it's possible (create expression with ref return) ... – Selvin Oct 19 '22 at 11:59
  • The first problem is that your delegate type doesn't return a `ref`. You'll have to declare your own delegate type: `public delegate ref TField RefReturner(T obj);` – canton7 Oct 19 '22 at 12:21
  • 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 – canton7 Oct 19 '22 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 – Marc Gravell Oct 19 '22 at 12:29
  • @MarcGravell I see, so can DynamicMethod(ILGenerator) do this? – uchifune Oct 19 '22 at 12:57
  • 1
    at that point you're just talking `ILGenerator`, and yes: `ILGenerator` can handle both managed and unmanaged pointers just fine – Marc Gravell Oct 19 '22 at 13:42

0 Answers0