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()
{
}
}
}
This is for exactly the same reason that you aren’t allowed to have:
The
+=operator, for delegates, is a combination. It is allowed with events (where it maps to theaddaccessor) and fields/variables (as long as the variable is assigned) (where it maps toDelegate.Combine)It you really want to use
+=, try:However, the following is easier: