Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is meant by delegates in .Net ?? (with Ex.)

user-image
Question added by Muhammed Effat Ahmed Afifi , Project Leader [Microsoft Business Unit] , Wipro Arabia Limited
Date Posted: 2013/04/17
Panneer selvam xavier
by Panneer selvam xavier , Supply Chain Analyst / Trainer , Infonet

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 secure.
Ex: shows how to declare, instantiate, and call a delegate.
//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, paperBack)); } // Call a passed-in delegate on each paperback book to process it: public void ProcessPaperbackBooks(ProcessBookDelegate processBook) { foreach (Book b in list) { if (b.Paperback) // Calling the delegate: processBook(b); } } } } // 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: AddBooks(bookDB); // Print all the titles of paperbacks: Console.WriteLine("Paperback Book Titles:"); // Create a new delegate object associated with the static // method Test.PrintTitle: bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(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: bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal)); Console.WriteLine("Average Paperback Book Price: ${0:#.##}", totaller.AveragePrice()); } // 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); } } }

Ahamed Aslam AB
by Ahamed Aslam AB , Software Architect , IBT Apps

Basically it is similar like the old "C" age function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions.
C# delegate is the smarter version of function pointer which helps software architects a lot, specially while utilizing design patterns.
At first, a delegate is defined with a specific signature (return type, parameter type and order etc).
To invoke a delegate object, one or more methods are required with the EXACT same signature.
A delegate object is first created similar like a class object created.
The delegate object will basically hold a reference of a function.
The function will then can be called via the delegate object.
public delegate int Calculate (int value1, int value2); public int add(int value1, int value2) { return value1 + value2; } public int sub( int value1, int value2) { return value1 - value2; } MyClass mc = new MyClass(); Calculate add = new Calculate(mc.add); Calculate sub = new Calculate(mc.sub); Console.WriteLine("Adding two values: " + add(10,6)); Console.WriteLine("Subtracting two values: " + sub(10,4));

Mohammed Rizwan Afgani
by Mohammed Rizwan Afgani , Software Engineer, Team Lead , Prosoft e-Solutions (I) Pvt Ltd

Delegate allows the programmer to encapsulate a reference to a method (i.e., having same signature) 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.
Advantages of using delegate: You want to call series of method by using single delegate without writing lot of method calls You want to implement event based system elegantly.
You want to call two methods same in signature but reside in different classes You want to pass method as a parameter You don't want to write lot of polymorphic code A Delegate Usage Example namespace MyDelegateEx { //This delegate can point to any method, //taking two integers and returning an //integer.
public delegate int MyDelegate(int x, int y); //This class contains methods that MyDelegate will point to.
public class MyClass { public static int Add(int x, int y) { return x + y; } public static int Multiply(int x, int y) { return x * y; } } class Program { static void Main(string[] args) { //Create an Instance of MyDelegate //that points to MyClass.Add().
MyDelegate del1 = new MyDelegate(MyClass.Add); //Invoke Add() method using the delegate.
int addResult = del1(5,5); Console.WriteLine("5 +5 = {0}\n", addResult); //Create an Instance of MyDelegate //that points to MyClass.Multiply().
MyDelegate del2 = new MyDelegate(MyClass.Multiply); //Invoke Multiply() method using the delegate.
int multiplyResult = del2(5,5); Console.WriteLine("5 X5 = {0}", multiplyResult); Console.ReadLine(); } } }

More Questions Like This