Search code examples
c#methodsextension-methods

Invoke an extension method on a method without a explicit reference


Is there any way to invoke an extension method on a method, but without a explicit reference?

For example, if I have a extension method:

public static class Extensions {
    public static void FooOn(this Func<string> method) =>
        Console.WriteLine($"Foo on {method()}");
}

I thought maybe I could do something like this, but perhaps not.

class Program {
    private string Bar() => "you"; 
    void Main() => Bar.FooOn();  // won't compile
}

Instead it seems I have to declare a temporary reference:

class Program {
    private string Bar() => "you"; 
    void Main(){
        Func<string> temp = Bar;
        temp.FooOn();
    }
}

So is there any way to invoke an extension method on a method, but without a explicit reference?


Solution

  • No, you can't, as it is a method, which cannot be used with extension methods.

    There are several workarounds (.NET Fiddle):

    1. As already mentioned in the question, you can create a temporary variable, which references the method:
      Func<string> temp = Bar;
      temp.FooOn();
      
    2. You can explicitly cast Bar to a Func<string>:
      static void Main() => ((Func<string>)Bar).FooOn();
      
    3. You call the extension method directly, passing Bar as a parameter:
      static void Main() => Extensions.FooOn(Bar);
      
    4. You store Bar as a Func<string> variable:
      static Func<string> Bar = () => "you"; 
      static void Main() => Bar.FooOn();