C# Delegates Introduction


This entry is part 1 of 8 in the series C# Delegates

When you first study delegates in C#, there is sometimes difficulty in under standing them. The book C# 6 and the .NET 4.6 Framework by Andrew Troelsen and Philip Japikse says: “The .NET delegate type is a type-safe object that “points to” a method or a list of methods that can be invoked at a later time. Unlike a traditional C++ function pointer, however, .NET delegates are classes that have built-in support for multicasting and asynchronous method invocation.” .NET delegates can point to either static or instance methods.

We have a post called C# Introduction.

There is a YouTube video by Packt Publishing that covers delegates. The video is part of a course that is offered at Packt and at Udemy.com. The video is called C# 7 and .NET Core 2.0 Recipes : Delegates and Lambda Expressions. I don’t cover that example here, but I include the link because I find that having the same thing explained in different ways can increase the chances of you learning and retaining the information.

  • A delegate is a pointer to a function/method or group of functions with a specific signature.
  • A delegate is an object that contains an ordered list of methods with the same signature and return type. The list of methods is called the invocation list.
  • A delegate is an object that holds one or more methods. A delegate is different from a typical object. You can execute a delegate, and when you do so, it executes the method or methods that it “holds.”

Every delegate in the .NET Framework (including your custom delegates) is automatically endowed with the ability to call its methods synchronously or asynchronously. The C# delegate keyword represents a sealed class deriving from System.MulticastDelegate.

A delegate maintains three important pieces of information:

  • The address of the method on which it makes calls
  • The parameters (if any) of this method
  • The return type (if any) of this method

The Simplest Possible Delegate Example

using System;
namespace SimpleDelegate
{
    class Program
    {
        // This delegate can point to ANY method that
        // takes two integers and returns an integer.
        public delegate int BinaryOp(int x, int y);
        // This class contains methods BinaryOp will point to
        public class SimpleMath
        {
            public static int Add(int x, int y)
               { return x + y; }
            public static int Subtract(int x, int y)
               { return x - y; }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("** Simple Delegate Example **");
            Console.WriteLine("based on the book C# 6 and the .NET 4.6 Framework\n");
            // Create a BinaryOp delegate object that
            // "points to" SimpleMath.Add().
            BinaryOp a = new BinaryOp(SimpleMath.Add);
            BinaryOp s = new BinaryOp(SimpleMath.Subtract);
            // Invoke Add() method indirectly using delegate object.
            Console.WriteLine("10 + 10 is {0}", a(10, 10));
            Console.WriteLine("10 + 10 is {0}", SimpleMath.Add(10, 10));
            Console.WriteLine("10 - 8 is {0}", s(10, 8));
        }
    }
}

Just a few changes to the above program. We can nest them.

using System;
namespace SimpleDelegatePart2
{
    class Program
    {
        // This delegate can point to any method,
        // taking two integers and returning an integer.
        public delegate int BinaryOp(int x, int y);
        // This class contains methods BinaryOp will point to
        public class SimpleMath
        {
            public static int Add(int x, int y) { return x + y; }
            public static int Subtract(int x, int y) { return x - y; }
            public static int Multiply(int x, int y) { return x * y; }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("** Simple Delegate Example **");
            Console.WriteLine("based on the book C# 6 and the .NET 4.6 Framework\n");
            // Create a BinaryOp delegate object that
            // "points to" SimpleMath.Add().
            BinaryOp a = new BinaryOp(SimpleMath.Add);
            BinaryOp m = new BinaryOp(SimpleMath.Multiply);
            // Invoke Add() method indirectly using delegate object.
            Console.WriteLine("10 + 10 is {0}", a(10, 10));
            Console.WriteLine("17 ---> 3 * 4 + 5 is: {0}", a(m(3,4),5));
        }
    }
}

The output.

Series NavigationC# Delegates Part 2 >>