question

Lancis007-9977 avatar image
0 Votes"
Lancis007-9977 asked Lancis007-9977 commented

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

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++;
             }
         }
     }
 }


dotnet-csharpdotnet-standarddotnet-console
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

cooldadtx avatar image
0 Votes"
cooldadtx answered Lancis007-9977 commented

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you so much for the code Sir.

0 Votes 0 ·