D
D
Denis Bredun2020-07-06 03:03:39
C++ / C#
Denis Bredun, 2020-07-06 03:03:39

C# What happens when we pass a delegate to a method and add 2 methods to it?

I'm doing an experiment right now:

class Program
{   
    delegate void Operation();
    public static void Main()
    {
         Operation op = DoSomething;
         Update(op); 
         op(); \\DoSomething();
    }
    public static void Update(Operation op)
    {
          op += DoSomething2;
          op += DoSomething3;
          op(); \\DoSomething();, DoSomething2();, 
                  \\DoSomething3();
    }
    public static void DoSomething()
    {

    }
    public static void DoSomething2()
    {

    }
    public static void DoSomething3()
    {

    }
}

I read Jeffrey Richber, so I know how a delegate works and what it is like when we create it, but I don’t understand what happens when we add methods to a delegate in a method. I don’t understand not in the sense what happens in the delegate itself, but I don’t understand what happens in memory, stack and heap, because we passed a reference to the delegate and it, in theory, should have changed, but did not change. Why? What happened on the heap and stack at the time the Update method was executed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2020-07-06
@Luffy1

I wrote to you yesterday in your question about the lines I wrote, and so here it goes the same way. Before calling the function, your delegate reference is duplicated on the stack. Since delegates are immutable, each time you add a method to a delegate, a new delegate will be created and a reference will be written to a copy invisible to you, without touching the variable. This is protection against unexpected behavior. Same behavior as with strings. If you want magic, pass the parameter via ref.
Yes, and frame the code in tags.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question