Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# delegate not working as it should?

Tags:

c#

delegates

im kinda new to c#, so I came up with this problem. Question: why is func2 called? oh, and one more thing. say I add a function to a delegate. In this function I call another delegate, however I want to make sure that every other function added to the first delegate is called before this function calls this delegate, is there any clean solution ( not really interested in getInvocationList). Thanks guys, you're the best.

class Program
{
    delegate void voidEvent();
    voidEvent test;

    private void func1()
    {
        Console.Write("func1");
        test -= func2;
    }

    private void func2()
    {
        Console.WriteLine("func2");
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        p.test += p.func1;
        p.test += p.func2;
        p.test();
    }
}
like image 869
Yamcha Avatar asked Apr 05 '12 23:04

Yamcha


1 Answers

Every time you change a delegate (+= or -=), you're effectively creating an entire copy of the invocation list (the methods that will get called).

Because of that, when you call p.test();, you're going to invoke every delegate in the invocation list at that point in time. Changing this inside of one of those handlers will change it for the next call, but won't change the currently executing call.

like image 123
Reed Copsey Avatar answered Oct 15 '22 00:10

Reed Copsey