C# Is this a correct use of Delegate and Callback method using delegate

Lancis007 41 Reputation points
2021-08-23T14:20:08.79+00:00

This code perfoms well.

I'm busy learning delegates in C# and merely want to know whether this is the correct use of Delegate and Callback method using delegate.

using System;

namespace DelegatesCallbackRealDemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Del handler = DelegateMethod;
            DataProgression(1, handler);

            Console.Read();
        }

        static void DelegateMethod(string message)
        {
            Console.WriteLine("Progression : " + message + " %");
            DelegateMethodPause(1);
        }


        static void DelegateMethodPause(int sec)
        {
            System.Threading.Thread.Sleep(sec*1000);
        }

        static void DataProgression(int param1, Del callback)
        {
            for (int i = 0; i < 100; i++)
            {
                callback(param1.ToString());
                param1++;
            }
        }
    }
}
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,346 questions
.NET CLI
.NET CLI
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
322 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,204 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 47,716 Reputation points
    2021-08-23T14:49:41.587+00:00

    Yes that is the correct approach on how delegates would work. A delegate is simply a function object and allows you to pass functions around as data.

    As an aside you should rarely need to declare the delegate type(s) yourself and instead rely on the pre-defined ones. This reduces your code and speeds things up. .NET already provides delegates for any method that accepts up to 16 parameters (at last check) and optionally return a value.

    Action<...> - void returning functions
    Func<...,T> - T returning functions

       static void DataProgression(int param1, Action<string> callback)  
        {  
            for (int i = 0; i < 100; i++)  
            {  
                 callback(param1.ToString());  
                 param1++;  
            }  
        }  
         
       //Long form  
       Action<string> foo = DelegateMethod;  
       DataProgression(1, foo);  
         
       //Short form  
       DataProgression(1, DelegateMethod);  
         
       //Short, short form  
       DataProgression(1, x => Console.WriteLine(x));  
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful