Using delegates to pass functions as arguments. - CSharp Custom Type

CSharp examples for Custom Type:delegate

Description

Using delegates to pass functions as arguments.

Demo Code

using System;// w  w  w  .  j  a  v a  2  s .  c o  m
using System.Collections.Generic;
class Delegates
{
   public delegate bool NumberPredicate(int number);
   static void Main()
   {
      int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      NumberPredicate evenPredicate = IsEven;
      Console.WriteLine($"Call IsEven using a delegate variable: {evenPredicate(4)}");
      // filter the even numbers using method IsEven
      List<int> evenNumbers = FilterArray(numbers, evenPredicate);
      DisplayList("\nUse IsEven to filter even numbers: ", evenNumbers);
      // filter the odd numbers using method IsOdd
      List<int> oddNumbers = FilterArray(numbers, IsOdd);
      DisplayList("\nUse IsOdd to filter odd numbers: ", oddNumbers);
      // filter numbers greater than 5 using method IsOver5
      List<int> numbersOver5 = FilterArray(numbers, IsOver5);
      DisplayList("\nUse IsOver5 to filter numbers over 5: ", numbersOver5);
   }
   // select an array's elements that satisfy the predicate
   private static List<int> FilterArray(int[] intArray, NumberPredicate predicate)
   {
      // hold the selected elements
      var result = new List<int>();
      // iterate over each element in the array
      foreach (var item in intArray)
      {
         // if the element satisfies the predicate
         if (predicate(item)) // invokes method referenced by predicate
         {
            result.Add(item); // add the element to the result
         }
      }
      return result; // return the result
   }
   // determine whether an int is even
   private static bool IsEven(int number) => number % 2 == 0;
   // determine whether an int is odd
   private static bool IsOdd(int number) => number % 2 == 1;
   // determine whether an int greater than 5
   private static bool IsOver5(int number) => number > 5;
   private static void DisplayList(string description, List<int> list)
   {
      Console.Write(description); // display the output's description
      // iterate over each element in the List
      foreach (var item in list)
      {
         Console.Write($"{item} "); // print item followed by a space
      }
   }
}

Result


Related Tutorials