Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# adding objects (similar to delegates)

I want to ask, can you do something similar to this?

Event += eventInstance;

Event is a class

I want to do something similar to delegates:

Write write1 = new Write(() => Console.WriteLine("Write1"));
Write write2 = new Write(() => Console.WriteLine("Write2"));
Write write3 = new Write(() => Console.WriteLine("Write3"));

Write write = write1 + write2 + write3;
write();

Thanks.

like image 220
TheAJ Avatar asked Dec 30 '11 02:12

TheAJ


2 Answers

Overload the + operator and combine the delegates. Something like this:

public class Write
{
    private readonly Action _act;

    public Write(Action act)
    {
        _act = act;
    }

    public void Invoke()
    {
        _act();
    }

    public static Write operator +(Write left, Write right)
    {
        //Do appropriate null-checking.
        var del = (Action)Delegate.Combine(left._act, right._act);
        return new Write(del);
    }
}

And using it like so:

Write write1 = new Write(() => Console.WriteLine("Write1"));
Write write2 = new Write(() => Console.WriteLine("Write2"));
Write write3 = new Write(() => Console.WriteLine("Write3"));

Write writeall = write1 + write2 + write3;
writeall.Invoke();

Will print

Write1
Write2
Write3
like image 61
vcsjones Avatar answered Oct 02 '22 15:10

vcsjones


You need to implement operator overloading for your class.

class Write
{
    public static Write operator +(Write w1, Write w2)
    {
        // implementation, must return Write object
    }
}
like image 24
Tomislav Markovski Avatar answered Oct 02 '22 15:10

Tomislav Markovski