What is the Invoke property on Func <T>?

This compiles, but the second method is marked as "The function is recursive on all paths." and calling it throws a StackOverflowException. Intellisense (w / ReSharper) provided Invoke as a property.

public class Class1 { public void MyMethod(string value) { Console.WriteLine(value); } public void MyMethod(Func<string> getValue) { MyMethod(getValue.Invoke); } } 

Changing it to this works as expected:

  public void MyMethod(Func<string> getValue) { MyMethod(getValue.Invoke()); } 

What's going on here? Is this just a weird oddity or is there an Invoke property?

+4
source share
2 answers

This is an Invoke method, but is converted using a method group transformation ... which is then recursed. See if this makes it clearer - this is the equivalent code:

 public void MyMethod(Func<string> getValue) { Func<string> func = getValue.Invoke; MyMethod(func); // Eek, recursive! } 

(I assume at the moment that you are familiar with converting a group of methods as one of the ways to get a delegate instance. Let me know if you don't, and I'll tell you more.)

+9
source

To add an answer to Jon, note that the reason you cannot find the Invoke member in the object browser is because in docs :

Note

The runtime provides an Invoke method for each delegate type, with the same signature as the delegate. You should not call this method explicitly from C #, Visual Basic, or Visual C ++, because compilers call it automatically. The Invoke method is useful in thinking when you want to find the signature type of a delegate.

-2
source

All Articles