Core C#

Delegate Operators

This C# program demonstrates how the delegate operator is used. A delegate is a method type that is defined to used like other data types.

Program.cs

using System;
using System.Collections.Generic;

namespace XoaX {
    class Program {
        public class CEvangelist {
            public string msName;
            public string msSymbol;
        }

        delegate void FnE(CEvangelist qEvangelist);

        static void SumOfSizes(CEvangelist qE) {
            Console.Write("Sum = " + (qE.msName.Length + qE.msSymbol.Length));
        }
        static void ProductOfSizes(CEvangelist qE) {
            Console.WriteLine("  Product = " + (qE.msName.Length * qE.msSymbol.Length));
        }

        static void Main(string[] args) {
            List<CEvangelist> qaEvangelists = new List<CEvangelist>() {
                new CEvangelist() { msName = "Matthew", msSymbol = "Man" },
                new CEvangelist() { msName = "Mark", msSymbol = "Lion" }, 
                new CEvangelist() { msName = "Luke", msSymbol = "Ox" }, 
                new CEvangelist() { msName = "John", msSymbol = "Eagle" }
            };
            Console.WriteLine("Delegate:");
            // A multicast delegate
            FnE fnMultiCast = SumOfSizes;
            fnMultiCast += ProductOfSizes;
            foreach (CEvangelist qCurr in qaEvangelists) {
                fnMultiCast(qCurr);
            }
        }
    }
}
 

Output

Delegate:
Sum = 10  Product = 21
Sum = 8  Product = 16
Sum = 6  Product = 8
Sum = 9  Product = 20
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.