What are the differences between these two classes? Which is preferable?
class MulticastExample
{
delegate void ME();
ME me;
public MulticastExample()
{
ME a = new ME(() => Console.WriteLine("A"));
ME b = new ME(() => Console.WriteLine("B"));
me = a + b;
}
public void Run()
{
me();
}
}
–
class ListExample
{
delegate void LE();
List<LE> le = new List<LE>();
public ListExample()
{
LE a = new LE(() => Console.WriteLine("A"));
LE b = new LE(() => Console.WriteLine("B"));
le.Add(a);
le.Add(b);
}
public void Run()
{
foreach (var x in le)
{
x();
}
}
}
With
MulticastExample,a single call tomewould call all the methodssubscribedto it.Soaandbwould be called through a single call tomeWith
ListExampleyou would have to call each of the delegates individually.So you would have to individually invokeaandbwhich you are doing in theforeachloopIf
aandbare going to refer to a single method of the same signature thenListExampleis redundant.You should useMulticastExample.