Search code examples
c#func

C# Func with Lambda Expressions


I am struggling to get my head around some c# codes. I am trying to find the documentation that provides the Syntax description for such usage of Func Delegates.

public class Person 
{
 public string name {get; set;}
 public int Age {get; set:}
}
           
Func<Person, bool> IsOlderOrEqual(int age) =>
                pm => pm.Age >= age;

From interpreting the syntax documentation, my understanding was, the parameter had to be type T which is Person in this case.

public delegate TResult Func<in T, out TResult>(T arg);

I have also come across codes like

 Func<SomeClass, bool> isActiveSelector = it => it.IsActive;

I am wondering if there is documentation from Microsoft about different syntax variations used for Func delegate, specially in conjunction with lambda operators.


Solution

  • Func<Person, bool> IsOlderOrEqual(int age) => pm => pm.Age >= age; is a method that returns Func<Person, bool> and is expression-bodied. It can be rewritten as

    Func<Person, bool> IsOlderOrEqual(int age)
    {
        return pm => pm.Age >= age;
    }
    

    Func<SomeClass, bool> isActiveSelector = it => it.IsActive; is a variable of type Func<SomeClass, bool> that is initialized with the value it => it.IsActive.