Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Noobie Delegate Fundamentals C#

Tags:

c#

delegates

I dont think I understand the point of a delegate method. All the examples I have seen do something like this:

class DelegateClass
{
    private List<string> ListString = new List<string>;
    delegate void DoSomethingToStringsDelegate(string s);

    public base()
    {
         ListString.Add("string"); ....
    }

    void ProcessStrings(DoSomethingToStringsDelegate dstsd)
    {
        foreach(string s in ListString)
            dstsd(s);
    }
}

class AClass
{
    ...
    void UseDelegateMethod(...)
    {
        DelegateClass ds = new DelegateClass();
        ds.ProcessStrings(new DoSomethingToStringsDelegate(PrintStrings);
    }
    void PrintStrings(string s)
    {
        System.out.Write(s);
    }
}

I dont understand why this is needed when you could simply just implement a getListStrings() and iterate through the strings yourself, doing what you needed to do, as if it was a delegate.

foreach( string s in ds.ggetListStrings() )
    System.out.Write(s);

Private members reason doesnt make sense because I could just do:

global List<Strings> myListStrings = new List<Strings>();
ds.ProcessStrings(new DoSomethingToStringsDelegate(GetStrings);

void GetStrings(string s)
{
    myListStrings.Add(s);
}

...and now I have the same list, as a getListStrings() would do ....

Can someone please explain? Thanks so much!

like image 221
Tizz Avatar asked Feb 22 '23 09:02

Tizz


1 Answers

The delegate is useful because it actually acts as a placeholder for any method that takes a string as parameter and returns void.

If you are familiar with C, it is similar to how a function pointer works. In its place you can pass any method that matches the signature and return type.

For example let's say I want to implement a method that sorts a group of objects. In addition to the object list I can also pass a delegate that indicates how the sort is to be done. Since any method matching the delegate can be passed, I can then dynamically switch between different methods if I want for example decreasing or increasing sort:

 delegate int comparisonDelegate(int p1, int p2);

 void SortArray(int[] array, comparisonDelegate cmp)
 {
      // determine order according to cmp
 }

 int CompareDecreasing(int p1, int p2)
 {
     if(p1 > p2) return -1;
     if(p1 < p2) return 1;
     return 0;
 }

 int CompareIncreasing(int p1, int p2)
 {
     if(p1 > p2) return 1;
     if(p1 < p2) return -1;
     return 0;
 }

Now I can call SortArray as:

 SortArray(array, new comparisonDelegate(compareDecreasing));
 SortArray(array, new comparisonDelegate(compareIncreasing));
like image 64
Tudor Avatar answered Mar 01 '23 23:03

Tudor