Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing multiple methods using one delegate

Tags:

c#

delegates

I'm currently sandpitting delegates.
In the following example does dd reference p.m and p.n ?
Can I add another line to run p.m again after adding p.n ? Or do I need to implement d dd = p.m; again?

class Program
{
    private delegate int d(int x);

    static void Main(string[] args)
    {
        Program p;
        p = new Program();

        d dd = p.m;//d dd = new d(p.m);
        Console.WriteLine(dd(3).ToString());

        dd += p.n;//dd += new d(p.n);
        Console.WriteLine(dd(3).ToString());

        //<<is there now a quick way to run p.m ?

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }

    private int m(int y)
    {
        return y * y;
    }
    private int n(int y)
    {
        return y * y - 10;
    }
}
like image 865
whytheq Avatar asked Feb 23 '26 17:02

whytheq


1 Answers

yes, after first assignment (d dd = this.m;), all assignment made using += will also be called.

You may just remove a method, using -=, refer to the following sample;

d dd = p.m;//d dd = new d(p.m);
Console.WriteLine(dd(3).ToString()); //calls p.m

dd += p.n;//dd += new d(p.n);
Console.WriteLine(dd(3).ToString()); //calls boths p.m and p.n

dd -= p.n;
Console.WriteLine(dd(3).ToString()); // only calls p.m
like image 59
daryal Avatar answered Feb 26 '26 07:02

daryal