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:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With