Home > Mobile >  Why the activation of this Func works?
Why the activation of this Func works?

Time:01-25

I can't understand how this is working.

Test expects to get a method with the signature of InterfaceObj as input, but we never pass it in Test2 (the Test itself holds a reference to Actual that implements InterfaceObj and acts as the input, but Test2 doesn't know it.. or is it?)

Actual implements InterfaceObj.

public bool Test(Func<InterfaceObj, bool> pointerToMethod)
{
    Actual actual = new Actual();

    return pointerToMethod(actual);
}

public bool Test2()
{
    return Test(x => x.Test());
}

CodePudding user response:

The type of the lambda parameters can be automatically inferred by the compiler. You could also specify the type explicitly:

public bool Test2()
{
    return Test((InterfaceObj x) => x.Test());
}

x => y can be assigned to a Func<T, TResult> with x being type T and y being type TResult.

And since your method Test() only accepts Func<InterfaceObj, bool>, x can only be of type InterfaceObj.

It also works when assigning a variable:

Func<InterfaceObj, bool> myFunction = x => x != null; // x is of type InterfaceObj

The lambda itself is not called, you still need to invoke it:

InterfaceObj obj = ...;
bool result1 = myFunction.Invoke(obj);
// or, shorter:
bool result2 = myFunction(obj);

NB Instead of Func<T, bool>, it is usually better to use the more specific Predicate<T> which also provides more semantic value to callers of your method.

  •  Tags:  
  • c#
  • Related