Skip to main content
added 80 characters in body
Source Link
Jon Skeet
  • 1.5m
  • 893
  • 9.3k
  • 9.3k

As you can see, I am passing the delegate reference to the object I created.

Yes, but you're then using:

greetings += new Action(SecondGreeting); 

This creates a new delegate - it doesn't change the existing delegate. Delegates are immutable, like strings. If you really want the code to work the way you'd expected, you'd have to use:

public void AddGreeting(ref Action greetings) { greetings += new Action(SecondGreeting); } 

and call it as

test.AddGreeting(ref greetings); 

(Or return a reference to the the new delegate, as shown in Peter's answer.)

See my article on delegates and events for more details about what += does.

As you can see, I am passing the delegate reference to the object I created.

Yes, but you're then using:

greetings += new Action(SecondGreeting); 

This creates a new delegate - it doesn't change the existing delegate. Delegates are immutable, like strings. If you really want the code to work the way you'd expected, you'd have to use:

public void AddGreeting(ref Action greetings) { greetings += new Action(SecondGreeting); } 

and call it as

test.AddGreeting(ref greetings); 

See my article on delegates and events for more details about what += does.

As you can see, I am passing the delegate reference to the object I created.

Yes, but you're then using:

greetings += new Action(SecondGreeting); 

This creates a new delegate - it doesn't change the existing delegate. Delegates are immutable, like strings. If you really want the code to work the way you'd expected, you'd have to use:

public void AddGreeting(ref Action greetings) { greetings += new Action(SecondGreeting); } 

and call it as

test.AddGreeting(ref greetings); 

(Or return a reference to the the new delegate, as shown in Peter's answer.)

See my article on delegates and events for more details about what += does.

Source Link
Jon Skeet
  • 1.5m
  • 893
  • 9.3k
  • 9.3k

As you can see, I am passing the delegate reference to the object I created.

Yes, but you're then using:

greetings += new Action(SecondGreeting); 

This creates a new delegate - it doesn't change the existing delegate. Delegates are immutable, like strings. If you really want the code to work the way you'd expected, you'd have to use:

public void AddGreeting(ref Action greetings) { greetings += new Action(SecondGreeting); } 

and call it as

test.AddGreeting(ref greetings); 

See my article on delegates and events for more details about what += does.