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?
No, you can't, as it is a method, which cannot be used with extension methods.
There are several workarounds (.NET Fiddle):
Func<string> temp = Bar;
temp.FooOn();
Bar
to a Func<string>
:
static void Main() => ((Func<string>)Bar).FooOn();
Bar
as a parameter:
static void Main() => Extensions.FooOn(Bar);
Bar
as a Func<string>
variable:
static Func<string> Bar = () => "you";
static void Main() => Bar.FooOn();