delegates lambda expressions c# code example

Example 1: the key concepts of delegates, events and lambda expressions;

using System;
using System.Linq;

public class Program
{
    public delegate string Reverse(string s);

    static string ReverseString(string s)
    {
        return new string(s.Reverse().ToArray());
    }

    static void Main(string[] args)
    {
        Reverse rev = ReverseString;

        Console.WriteLine(rev("a string"));
    }
}

Example 2: c# delegate lambda

// ------------ DELEGATE, ANONYMOUS FUNCTIONS and LAMBDA ------------ //

// DELEGATE:

public class Program
{
    // Delegate
    public delegate double MathOperation(double x, double y);
  
	// 1º Method
    static double Addition(double x, double y)
    {
        return x + y;
    }
  
	// 2º Method 
    static double Multiply(double x, double y)
    {
        return x * y;
    }

  	// 3º Method 
    static double Subtration(double x, double y)
    {
        return x - y;
    }

    // Main
    static void Main(string[] args)
    {	
      
      	// Normal Delegate:
      
        MathOperation myFunction = Addition;  

        Console.WriteLine("The math gives: " + myFunction(2.6, 8.0));
      
        MathOperation myFunction2 = Multiply;  

        Console.WriteLine("The math gives: " + myFunction2(7.9, 1.6));
      
      
        // Multicast Delegate:
      	
      	MathOperation multiFunction = Addition + Multiply;
      	multiFunction += Subtration;    // Add one more pointer to the method Subtration 
      
      	multiFunction(3.1, 4.5)  // It will call all 3 Methods with the same pair of parameters  
      
      	multiFunction -= Addition;   // Eliminate the pointer to the method Addition
      
        multiFunction(3.1, 4.5)  // It will call the Methods Multiply and Subtraction 
      
    }
}


// ANONYMOUS FUNCTIONS:

public class Program
{
    // Delegate
    public delegate double MathOperation(double x, double y);

    // Main
    static void Main(string[] args)
    {	
        // Anonymous function:
        MathOperation myFunction = delegate(double x, double y) { return x + y; };
      
        // You can also pass an anonymous function to methods:
      	Display(myFunction);
    }
  
  	static void Display(MathOperation myFoo)
    {
    	Console.WriteLine("The math gives: " + myFoo(2.8, 1.5));
      
    }

}
 

// LAMBDA:

public class Program
{
    // Delegate
    public delegate double MathOperation(double x, double y);

    // Main
    static void Main(string[] args)
    {	
        // Lambda function:
        MathOperation myFunction = (double x, double y) => { return x + y; };
        // OR
      	MathOperation myFunction2 = (x,y) => x * y;
    }
}