Website Links

Tuesday 24 January 2017

C# - Lambda Expressions

Lambda expressions are anonymous methods that have:
  • No access modifier
  • No name
  • No return statement

We use them for convenience so that we can write less code to achieve the same result. We also use them to make our code more readable. You can define a lambda expression as follows:

    // The generic types defined within the < and > represent the input
    // and output values, the first x types being the inputs
    // and the last type being the output 
    Func increment = number => number++;

    // You can call a lambda expression like this: 
    int incrementedNumber = increment(1);

    // A lambda expression with no arguments is defined like this: 
    Func greeting = () => "Hello world!";

    // A lambda expression with multiple arguments is defined like this: 
    Func add = (x, y) => x + y;

    // A lambda expression can also access variables in scope: 
    var name = "Chelsea";
    Func greetPerson = () => "Hello " + name;

    // This would print out "Hello Chelsea":   
    Console.WriteLine(greetPerson());

    // This would print out "Hello Tessa":   
    name = "Tessa";
    Console.WriteLine(greetPerson());



References

C# Lambda Expressions on YouTube https://youtu.be/SLPJ2GqF2Ts?t=5m14s

No comments:

Post a Comment