Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

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 +=

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata