Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Anonymous Methods

An anonymous method is one way to create an unnamed block of code that is associated with a specific delegate instance. An anonymous method is created by following the keyword delegate with a block of code. To see how this is done, let’s begin with a simple example. The following program uses an anonymous method that counts from 0 to 5.

// Demonstrate an anonymous method.

using System;

// Declare a delegate type.
delegate void CountIt();

class AnonMethDemo {

  static void Main() {

    // Here, the code for counting is passed
    // as an anonymous method.
    CountIt count = delegate {
        // This is the block of code passed to the delegate.
      for(int i=0; i <= 5; i++)
        Console.WriteLine(i);
    }; // notice the semicolon

    count();
  }
}


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint