Delegates – simple example parameterised code

This is just for me so I can easily find example notes.

One of my prime resources for learning C#:
Jamie King on YouTube

...

using System;

/// <summary>
/// Delegates - simple parameterised code "gauntlet"
/// </summary>
namespace ScratchPad
{

    delegate Boolean MeDelegate(int n);

    class MainClass
    {
        static bool LessThanFive(int n) { return n < 5; }
        static bool LessThanTen(int n) { return n < 10; }
        static bool GreaterThanThirteen(int n) { return n > 13; }
        static void Main()
        {
            int[] numbers = new[] { 2, 7, 3, 9, 5, 7, 1, 8 };

            var result = RunNumbersThroughGauntlet(numbers, LessThanTen);
            foreach (int n in result)
            {
                Console.WriteLine(n);
            }

        }


        static IEnumerable<int> RunNumbersThroughGauntlet(
               IEnumerable<int> numbers, MeDelegate gauntlet)
        {
            foreach (int number in numbers)
            {
                if (gauntlet(number))
                {
                    yield return number;
                }
            }
        }
    }
}

2
7
3
9
5
7
1
8
Press any key to continue . . .

Print Friendly, PDF & Email