Welcome to Shaun Luttin's public notebook. It contains rough, practical notes. The guiding idea is that, despite what marketing tells us, there are no experts at anything. Sharing our half-baked ideas helps everyone. We're all just muddling thru. Find out more about our work at bigfont.ca.

C# Delegate Notes

Tags: C#, .NET

C# Version 1

  • Declaring a delegate is similar to defining a class, struct, or interface. That is, we can define it inside or outside a class.
  • A delegate type specifies the parameter and return types that methods must have.
  • A delegate instance contains a list of methods that each have an appropriate signature.
  • We usually add methods to the invocation list with the += syntax.
  • When we invoke a delegate instance, we invoke all of its methods and receive the return value of the final method.
  • We stop invoking the method list if any method throws an exception.
  • Methods stored in a delegates invocation list have access to the members of the class that defined the method.

Events

  • An event must be declared as a delegate type.
  • We use += and -= to subscribe and unsubscribe to an event.
  • When we do this, we are calling the Add/Remove methods on the event's delegate type.

Sources

C# in Depth, Third Edition, Jon Skeet