Function function works in one direction and not in the other

I am trying to write a function that takes a function as one of its arguments - a task that I have done many times before. This works great:

int RunFunction(Func<int,int> f, int input) { return f(input); } int Double(int x) { return x*2; } // somewhere else in code RunFunction(Double,5); 

But this does not work:

 public static class FunctionyStuff { public static int RunFunction(this Func<int,int> f, int input) { return f(input); } } // somewhere else in code Double.RunFunction(5); 

Any idea why the first works and the second doesn't?

+6
source share
2 answers

The first version converts a group of methods as part of matching "argument to parameter". This conversion is not performed for extension methods. The same is true for lambda expressions - you could not write:

 ((int x) = > x * 2).RunFunction(10); 

or.

Section 7.6.5.2 of the C # 4 specification provides details about extension method calls. This begins by requiring the method to call one of the following forms:

 expr.identifier ( ) expr.identifier ( args ) expr.identifier < typeargs > ( ) expr.identifier < typeargs > ( args ) 

This rule uses the expression type ( expr ):

The extension method C i .M j is eligible if

  • [...]
  • An implicit conversion of an identity, reference, or box exists from expr to the type of the first parameter M j .

An annotated version of the specification then includes this comment from Eric Lippert:

This rule ensures that the creation of a method that extends double is not propagated by int either. It also ensures that anonymity methods are not defined for anonymous functions or groups of methods.

+5
source

Extension methods "invoked as if they were methods of an instance of an extended type."

In your case, Double not an instance, so you cannot call the extension method on it.

0
source

Source: https://habr.com/ru/post/911012/


All Articles