Chapter 4. Advanced C# Features

In this chapter, we cover advanced C# topics, including events, operator overloading, try statements and exceptions, attributes, unsafe code and pointers, preprocessor directives, and XML documentation.

Delegates

               attributes? unsafe? access-modifier?
new?
delegate
[ void | type ]
delegate-name (parameter-list);

A delegate is a type defining a method signature, so that delegate instances can hold and invoke a method or list of methods that match its signature. A delegate declaration consists of a name and a method signature. For example:

using System;
delegate bool Filter (string s);
  
class Test {
   static void Main( ) {
      Filter f = new Filter(FirstHalfOfAlphabet);
      Display(new String [ ] {"Ant","Lion","Yak"}, f);
   }
   static bool FirstHalfOfAlphabet(string s) {
      return "N".CompareTo(s) > 0;
   }
   static void Display(string[ ] names, Filter f) {
      int count = 0;
      foreach(string s in names)
         if(f(s)) // invoke delegate
            Console.WriteLine("Item {0} is {1}", count++, s);
   }
}

Note that the signature of a delegate method includes its return type. It also allows the use of a params modifier in its parameter list, which expands the list of elements that characterize an ordinary method signature. The actual name of the target method is irrelevant to the delegate.

Multicast Delegates

Delegates can hold and invoke multiple methods. In this example, we declare a very simple delegate called MethodInvoker, which we use to hold and then invoke the Foo and Goo methods sequentially. The += method creates a new delegate by adding the right delegate operand to the left delegate operand:

using System;
delegate void MethodInvoker( );
class Test {
   static void Main( ) {
       new Test( ); // prints "Foo","Goo"
   }
   Test ( ) {
      MethodInvoker m = null;
      m += new MethodInvoker(Foo);
      m += new MethodInvoker(Goo);
      m( );
   }
   void Foo( ) {
      Console.WriteLine("Foo");
   }
   void Goo( ) {
      Console.WriteLine("Goo");
   }
}

A delegate can also be removed from another delegate using the -= operator:

Test {
   MethodInvoker m = null;
   m += new MethodInvoker(Foo);
   m -= new MethodInvoker(Foo);
   // m is now null
}

Delegates are invoked in the order they are added. If a delegate has a nonvoid return type, then the value of the last delegate invoked is returned. Note that the += and -= operations on a delegate are not thread-safe. (For more information on thread safety, see Chapter 16.)

Tip

To work with the .NET runtime, C# compiles += and -= operations made on a delegate to the static Combine and Remove methods of the System.Delegate class.

Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.