Explenation of delegates?

ToostR 61 Reputation points
2022-03-21T04:16:28.633+00:00

I'm trying to develop a mod for Beat Saber, and I need to learn delegates and how to use them correctly. I looked at documentations and still, they don't make sense to me. All I know is something += anothersomething. So could someone please explain what delegates are used for, what situations they need to be used in, how to use them, and maybe some examples please. Thank you

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-03-21T08:32:41.483+00:00

    @ToostR ,Welcome to Microsoft Q&A, based on your description, you have some questions about delegates.

    The question When & why to use delegates? in stackoverflow is simliar to your problem and you could have a look.

    So could someone please explain what delegates are used for

    The first answer describes that By defining a delegate, you are saying to the user of your class, "Please feel free to assign any method that matches this signature to the delegate and it will be called each time my delegate is called".

    how to use them, and maybe some examples please

    You could refer to the second answer in the above link to guide you how to use delegate and it has a good code example to explain the delagate.

    what situations they need to be used in

    You could use the delegate when you meet one of the conditions:

    1. You want to call series of method by using single delegate without writing lot of method calls.
    2. You want to implement event based system elegantly.
    3. You want to call two methods same in signature but reside in different classes.
    4. You want to pass method as a parameter.
    5. You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method.

    Hope my explanation could helpful for you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2022-03-21T07:37:44.763+00:00

    MSDN docs are generally the best reference
    Delegates are well explained with examples : Using Delegates (C# Programming Guide)

    0 comments No comments

  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-03-21T10:39:23.58+00:00

    Sometimes the best way to learn is to have real-world examples. I've put some together found in the following project.

    For example, using an action delegate for assigning custom events for a TaskDialog

    185157-f1.png

    Example to report progress and immediately notification of a runtime error

    public static void InvokeError()  
    {  
        try  
        {  
            for (int index = 0; index < 20; index++)  
            {  
                Progress?.Invoke(index);  
                if (index == 12)  
                {  
                    throw new Exception("Intentional error");  
                }  
            }  
        }  
        catch (Exception exception)  
        {  
            ErrorHandler?.Invoke(exception);  
        }  
    }  
    

    And the typical samples

    public class ActionClass  
    {  
        public void InvokeLater(Action action)  
        {  
            action();  
        }  
        public void DoSomethingElse(int param1, string param2)  
        {  
            Debug.WriteLine($"Called in {nameof(DoSomethingElse)} Parameter1: {param1}\tParameter2 {param2}");  
        }  
        public void DoSomething(int parameter1, string parameter2)  
        {  
            Debug.WriteLine($"Called in {nameof(DoSomething)} Parameter1: {parameter1}\tParameter2 {parameter2}");  
        }  
      
        public delegate void SayAnything();  
        public readonly SayHello HelloFunction = () => Debug.WriteLine("Hello!");  
        public static readonly SayAnything HelloFunction2 = () => Debug.WriteLine("Hello!");  
        public static readonly SayAnything GoodbyeFunction2 = () => Debug.WriteLine("Goodbye!");  
        public static readonly Func<string, string, int> SumCharacters = (value1, value2) => value1.Length + value2.Length;  
        public delegate void SayHello();  
        public static readonly Action<string> GreetingsAction = (name) => Debug.WriteLine($"Hello {name}");  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.