Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delegate add and remove

Tags:

c#

delegates

I wrote a sample example ,

When I created a delegate instance like below

AddFunctions d1 += new AddFunctions(Function1); 

I got a compilation error and hence += was removed and created in this way

AddFunctions d1 = new AddFunctions(Function1);

I was just curious to know , Why it is not allowed to have multicast(+=) when a single delegate instance is created?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegates
{
    public delegate void AddFunctions();

    class Program
    {

        static void Main(string[] args)
        {
            AddFunctions d1 = new AddFunctions(Function1);
            d1 -= d1;
            d1();
        }

        static void Function1()
        {
        }

        static void Function2()
        {
        }
    }
}
like image 582
Raghav55 Avatar asked Jun 04 '26 20:06

Raghav55


1 Answers

This is for exactly the same reason that you aren't allowed to have:

int i += 1;

The += operator, for delegates, is a combination. It is allowed with events (where it maps to the add accessor) and fields/variables (as long as the variable is assigned) (where it maps to Delegate.Combine)

It you really want to use +=, try:

AddFunctions d1 = null;
d1 += Function1;

However, the following is easier:

AddFunctions d1 = Function1;
like image 148
Marc Gravell Avatar answered Jun 06 '26 09:06

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!