add and remove methods to delegate

T

Tony Johansson

Hello!!

I have a simple program below copied fram a book.
The program works and there is no problem with it.

The last line printed in this program writes Goodnight which come from
new Greeting(SayGoodnight);

Now to my question I see that I can remove an delegete instance by using for
example this
ourGreeting -= myGreeting; and add by using +=

How do I remove for example new Greeting(SayGoodnight);
from ourGreeting. Is that really possible without creating an delegete
instance like
Greeting nightGreeting = new Greeting(SayGoodnight); and then use this
construction
ourGreeting -= nightGreeting ;

using System;

class MulticastTester
{
delegate void Greeting();

public static void Main()
{
Greeting myGreeting = new Greeting(SayThankYou);
Console.WriteLine("My single greeting:");
myGreeting();

Greeting yourGreeting = new Greeting(SayGoodMorning);
Console.WriteLine("\nYour single greeting:");
yourGreeting();

Greeting ourGreeting = myGreeting + yourGreeting;
Console.WriteLine("\nOur multicast greeting");
ourGreeting();

ourGreeting += new Greeting(SayGoodnight);
Console.WriteLine("\nMulticast greeting which includes Goodnight:");
ourGreeting();

ourGreeting = ourGreeting - yourGreeting;
Console.WriteLine("\nMulticast greeting without you greeting:");
ourGreeting();

ourGreeting -= myGreeting;
Console.WriteLine("\nSingle greeting without your greeting and my
greeting:");
ourGreeting();
}

public static void SayThankYou()
{ Console.WriteLine("Thank you!"); }

public static void SayGoodMorning()
{ Console.WriteLine("Goodmorning!"); }

public static void SayGoodnight()
{ Console.WriteLine("Goodnight!"); }
}

//Tony
 
J

Jon Skeet [C# MVP]

How do I remove for example new Greeting(SayGoodnight);
from ourGreeting. Is that really possible without creating an delegete
instance like
Greeting nightGreeting = new Greeting(SayGoodnight); and then use this
construction
ourGreeting -= nightGreeting ;

Well, you could do it in one go:

ourGreeting -= new Greeting(SayGoodnight);

That will work fine.

There's no way of doing it without constructing a delegate instance
though.
 
B

Ben Voigt [C++ MVP]

Jon Skeet said:
Well, you could do it in one go:

ourGreeting -= new Greeting(SayGoodnight);

That will work fine.

There's no way of doing it without constructing a delegate instance
though.

Although C# 2 and later will do that for you, so you can write simply:

ourGreeting -= SayGoodnight;

There is still an invisible delegate instance created though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top