5

I'm looking for a method to convert instance of MemberInfo to "Func" type (to use it through lambda expression later).

Lets, say I have a member function of type

public bool func(int);

Using reflection, I somehow get instance of MemberInfo "mi", now i want to convert it to Func<int, bool>; type. something like:

Func<int, bool f = myType.GetMember(mi.Name);

Is there a way to do it?

ps. Marc Grawell's answer resolves my issue, no need for further comments

etwas77
  • 514
  • 1
  • 6
  • 17
  • Func is a function *on a specific instance*, whereas MemberInfo is not tied to an instance. Do you have the instance available in your code? – Heinzi Jul 30 '13 at 08:47
  • What target would you want to call it on? And do you know it's *always* going to return a `bool` and take an `int`? Basically look at `Delegate.CreateDelegate`... – Jon Skeet Jul 30 '13 at 08:47
  • You might want to check on your premise; "to use it through lambda expression later" - getting a delegate won't help you with a lambda expression – Marc Gravell Jul 30 '13 at 08:49

1 Answers1

6
Func<int,bool> f = (Func<int,bool>)Delegate.CreateDelegate(
           typeof(Func<int,bool>), target, (MethodInfo)mi);

or on more recent frameworks:

var f = mi.CreateDelegate<Func<int,bool>>(target);

Note here that target is the object you want to use, since func is a non-static method. If it was a static method, you can omit that (or pass null). Alternatively, you can omit target (or pass null) if you make it a Func<Foo, int, bool> where Foo is the type that declares func.

However!!! Note that having a Func<int,bool> is largely meaningless in terms of creating a lambda expression; lambda expressions rarely use delegates.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Out of curiosity, do you know if there any difference between the `Delegate.CreateDelegate` that you use and the `MethodInfo.CreateDelegate` that I put in my answer? –  Jul 30 '13 at 08:49
  • Can you clarify what you mean by your last statement, _"However…lambda expressions rarely use delegates."_? – stakx - no longer contributing Jul 30 '13 at 08:50
  • @hvd before .NET 4.5, a very big difference: `MethodInfo.CreateDelegate` doesn't exist – Marc Gravell Jul 30 '13 at 08:51
  • @stakx I'm interpreting the context here as relating to `Expression` types - expression trees. Those use `MethodInfo`, not delegates. – Marc Gravell Jul 30 '13 at 08:52
  • Hah, that's a good difference. :) In that case, I'll just vote for your answer and remove mine. –  Jul 30 '13 at 08:52
  • Note, on C#9 (and poss/prolly before) this produces a no-explicit-conversion error. So, either (cast) the result or use var. – stardotstar Jun 15 '23 at 13:59
  • @stardotstar also there's a more useful helper method from .net 5 onwards (see edit) – Marc Gravell Jun 15 '23 at 16:01