How do you declare delegates and are delegates and events
one and the same and explain how do you declare delegates
and invoke them ?

How do you declare delegates and are delegates and events one and the same and explain how do you d..

Answer / g.yasmin banu

A delegate in C# is similar to a function pointer in C or
C++. Using a delegate allows the programmer to encapsulate
a reference to a method inside a delegate object. The
delegate object can then be passed to code which can call
the referenced method, without having to know at compile
time which method will be invoked. Unlike function pointers
in C or C++, delegates are object-oriented, type-safe, and

A delegate declaration defines a type that encapsulates a
method with a particular set of arguments and return type.
For static methods, a delegate object encapsulates the
method to be called. For instance methods, a delegate
object encapsulates both an instance and a method on the
instance. If you have a delegate object and an appropriate
set of arguments, you can invoke the delegate with the

An interesting and useful property of a delegate is that it
does not know or care about the class of the object that it
references. Any object will do; all that matters is that
the method's argument types and return type match the
delegate's. This makes delegates perfectly suited
for "anonymous" invocation.

Note Delegates run under the caller's security
permissions, not the declarer's permissions.
This tutorial includes two examples:

Example 1 shows how to declare, instantiate, and call a
Example 2 shows how to combine two delegates.
In addition, it discusses the following topics:

Delegates and Events
Delegates vs. Interfaces

The following example illustrates declaring, instantiating,
and using a delegate. The BookDB class encapsulates a
bookstore database that maintains a database of books. It
exposes a method ProcessPaperbackBooks, which finds all
paperback books in the database and calls a delegate for
each one. The delegate type used is called
ProcessBookDelegate. The Test class uses this class to
print out the titles and average price of the paperback

The use of delegates promotes good separation of
functionality between the bookstore database and the client
code. The client code has no knowledge of how the books are
stored or how the bookstore code finds paperback books. The
bookstore code has no knowledge of what processing is done
on the paperback books after it finds them.

// bookstore.cs
using System;

// A set of classes for handling a bookstore:
namespace Bookstore
using System.Collections;

// Describes a book in the book list:
public struct Book
public string Title; // Title of the book.
public string Author; // Author of the book.
public decimal Price; // Price of the book.
public bool Paperback; // Is it paperback?

public Book(string title, string author, decimal
price, bool paperBack)
Title = title;
Author = author;
Price = price;
Paperback = paperBack;

// Declare a delegate type for processing a book:
public delegate void ProcessBookDelegate(Book book);

// Maintains a book database.
public class BookDB
// List of all books in the database:
ArrayList list = new ArrayList();

// Add a book to the database:
public void AddBook(string title, string author,
decimal price, bool paperBack)
list.Add(new Book(title, author, price,

// Call a passed-in delegate on each paperback book
to process it:
public void ProcessPaperbackBooks(ProcessBookDelegate
foreach (Book b in list)
if (b.Paperback)
// Calling the delegate:

// Using the Bookstore classes:
namespace BookTestClient
using Bookstore;

// Class to total and average prices of books:
class PriceTotaller
int countBooks = 0;
decimal priceBooks = 0.0m;

internal void AddBookToTotal(Book book)
countBooks += 1;
priceBooks += book.Price;

internal decimal AveragePrice()
return priceBooks / countBooks;

// Class to test the book database:
class Test
// Print the title of the book.
static void PrintTitle(Book b)
Console.WriteLine(" {0}", b.Title);

// Execution starts here.
static void Main()
BookDB bookDB = new BookDB();

// Initialize the database with some books:

// Print all the titles of paperbacks:
Console.WriteLine("Paperback Book Titles:");
// Create a new delegate object associated with
the static
// method Test.PrintTitle:

// Get the average price of a paperback by using
// a PriceTotaller object:
PriceTotaller totaller = new PriceTotaller();
// Create a new delegate object associated with
the nonstatic
// method AddBookToTotal on the object totaller:
Console.WriteLine("Average Paperback Book Price:

// Initialize the book database with some test books:
static void AddBooks(BookDB bookDB)
bookDB.AddBook("The C Programming Language",
"Brian W. Kernighan and Dennis M. Ritchie",
19.95m, true);
bookDB.AddBook("The Unicode Standard 2.0",
"The Unicode Consortium", 39.95m, true);
bookDB.AddBook("The MS-DOS Encyclopedia",
"Ray Duncan", 129.95m, false);
bookDB.AddBook("Dogbert's Clues for the Clueless",
"Scott Adams", 12.00m, true);

Code Discussion
Declaring a delegate The following statement:
Copypublic delegate void ProcessBookDelegate(Book book);
declares a new delegate type. Each delegate type describes
the number and types of the arguments, and the type of the
return value of methods that it can encapsulate. Whenever a
new set of argument types or return value type is needed, a
new delegate type must be declared.

Instantiating a delegate Once a delegate type has been
declared, a delegate object must be created and associated
with a particular method. Like all other objects, a new
delegate object is created with a new expression. When
creating a delegate, however, the argument passed to the
new expression is special — it is written like a method
call, but without the arguments to the method.
The following statement:

CopybookDB.ProcessPaperbackBooks(new ProcessBookDelegate
creates a new delegate object associated with the static
method Test.PrintTitle. The following statement:

creates a new delegate object associated with the nonstatic
method AddBookToTotal on the object totaller. In both
cases, this new delegate object is immediately passed to
the ProcessPaperbackBooks method.

Note that once a delegate is created, the method it is
associated with never changes — delegate objects are

Calling a delegate Once a delegate object is created, the
delegate object is typically passed to other code that will
call the delegate. A delegate object is called by using the
name of the delegate object, followed by the parenthesized
arguments to be passed to the delegate. An example of a
delegate call is:
A delegate can either be called synchronously, as in this
example, or asynchronously by using BeginInvoke and
EndInvoke methods.

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More ASP.NET Interview Questions

Types of objects in ASP?

8 Answers   Microsoft, Beget,

Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.

1 Answers  

Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one

1 Answers  

About CLS and CTS ?

3 Answers   Microsoft,

what is Theme in 2.0

1 Answers   Syntel,

How can you debug an ASP page, without touching the code?

1 Answers   Prodigy Technologies,

What is interval time of GC in .net

2 Answers  

What?s a bubbled event?

6 Answers   Visual Soft,

Explain the life cycle of an ASP .NET page

2 Answers   HCL, Surya Software,

What do you mean by authentication and authorization

2 Answers  

if i have a web page, and after the postback i dont to maintain the viewstate. How can we maintain in web application?

4 Answers   CGI,

You create an ASP.NET application for a hotel. The application contains a page that displays current weather conditions for the city in which the hotel is located. The application calls an XML Web service every 10 minutes to update the current weather conditions. A new page is then displayed for subsequent requests. You want the same page to be cached and retrieved from the cache during the time between calls to the XML Web service. You decide to use a Page directive to accomplish this goal. Which Page directive should you use? A . <%@ Cache Seconds="600 '' VaryByParam="Page" %> B . <%@ OutputCache Time="600" %> C . <%@ OutputCache Duration="600" VaryByParam="None" %> D . <%@ OutputCache Duration="600" %>

2 Answers   Syntax Softtech,