DEV Community

Cover image for Just learned the Concept of Delegates in C#
BALIGUAT, JUSTINE JERALD Y.
BALIGUAT, JUSTINE JERALD Y.

Posted on

Just learned the Concept of Delegates in C#

🚀 My Journey into Advanced C#: Understanding Delegates

I’m new to C#, and I recently completed the C# online tutorial from W3Schools. That gave me a solid foundation, but today I decided to level up by following an advanced C# programming course on YouTube by freeCodeCamp.

And today’s topic? Delegates.


🧠 What Are Delegates?

Delegates in C# are:

Type-safe, object-oriented method pointers.

In simple terms, a delegate allows you to pass a method as a parameter to another method. Think of it as storing a reference to a function inside a variable — but in a structured and safe way.


🏗 Creating and Using a Delegate

In the first part of the tutorial, I learned how to:

  • Create a delegate
  • Define its signature
  • Pass methods as parameters
  • Invoke the delegate

Here’s a visual reference:

Delegates Example


⚠️ Important Rule: Parameter Matching

One key concept I learned is this:

The delegate’s parameter types must match the parameter types of the method being assigned to it.

If the method signature doesn’t match the delegate signature, C# will throw a compile-time error. This is what makes delegates type-safe.

For example:

public delegate void MyDelegate(string message);

public static void ShowMessage(string text)
{
    Console.WriteLine(text);
}
Enter fullscreen mode Exit fullscreen mode

Delegate can also reference instance methods.

Below is the example code of a delegate referencing an instance method.

namespace DelegateBasicExample
{
    delegate void LogText(string text, DateTime datetime);
    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();
            LogText logTextToConsole = new LogText(logger.LogTextToConsole);

            Console.WriteLine("Enter some text: ");
            Console.WriteLine($"{DateTime.Now} : {Console.ReadLine()}");
        }
    }

    class Logger
    {
        public void LogTextToConsole(string text, DateTime datetime)
        {
            Console.WriteLine($"{datetime} : {text}");
        }

        public void LogTextToFile(string text, DateTime datetime)
        {
            using (StreamWriter sw = new StreamWriter("log.txt", true))
            {
                sw.WriteLine($"{datetime} : {text}");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Muti-cast delegate

Multiple objects can be assigned to one delegate instance by using the plus + operator. We're able to call multiple functions using one instance delegate.

namespace DelegateBasicExample
{
    delegate void LogText(string text, DateTime datetime);
    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();
            LogText LogTextToFile, LogTextToConsole;
            LogTextToFile = new LogText(logger.LogTextToFile);
            LogTextToConsole = new LogText(logger.LogTextToConsole);

            LogText multiLogText = LogTextToConsole + LogTextToFile;

            Console.WriteLine("Enter some text: ");
            multiLogText(Console.ReadLine(), DateTime.Now);
        }
    }

    class Logger
    {
        public void LogTextToConsole(string text, DateTime datetime)
        {
            Console.WriteLine($"{datetime} : {text}");
        }

        public void LogTextToFile(string text, DateTime datetime)
        {
            using (StreamWriter sw = new StreamWriter("log.txt", true))
            {
                sw.WriteLine($"{datetime} : {text}");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Delegate can also be passed as an argument to a method, then invoked by the method that receives the delegate argument.

    class Program
    {
        static void Main(string[] args)
        {
            Logger logger = new Logger();
            LogText LogTextToFile, LogTextToConsole;
            LogTextToFile = new LogText(logger.LogTextToFile);
            LogTextToConsole = new LogText(logger.LogTextToConsole);

            LogText multiLogText = LogTextToConsole + LogTextToFile;

            Console.WriteLine("Enter some text: ");
            LogWithDelParam(multiLogText, Console.ReadLine());
        }

        static void LogWithDelParam(LogText logText, string text)
        {
            logText(text, DateTime.Now);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)