.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh
Melody Anderson
Eminent IT

Home >> Code Snippets >> Design Patterns >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Simple Delegate

Posted By:Srikanth       Posted Date: November 18, 2010    Points: 15    Category: Design Patterns    URL: http://www.dotnetspark.com  

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. In my example i will create a DELEGATE first and then pass a method to that delegate as a parameter. If we encapsulate a single method then it is said to be SingleCastDelegate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateExample
    class Program
        //Intializing a Delegate Here(MULTICAST- Encapsulating more than one method)
        public delegate int Calculate(int value1, int value2);
        static void Main(string[] args)
            SriClass mc = new SriClass();
            //This is a MULTICAST Delegate
            Calculate add = new Calculate(mc.add);
            Calculate sub = new Calculate(mc.sub);
            Console.WriteLine("Addition of 2 Numbers ::" + add(100, 23));
            Console.WriteLine("Subtraction of 2 numbers :: " + sub(123, 23));
    //Creating a Class with methods inorder to invoke the Delegate Object With Same Signature(ReturnType+Prameters)
    class SriClass
        public int add(int value1, int value2)
            return value1 + value2;
        public int sub(int value1, int value2)
            return value1 - value2;


The above example is the simple sample to exaplain the concept of Delegate. I created a class with 2 different methods called add() and sub().. Which takes 2 parameters and does the operation of addition and subtraction of 2 numbers.

Hope this code will help the new ones who start Delegates...




Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend