Sample Code Snippet For Delegate

A delegate is almost like a function pointer.a delegate contains a reference to a method
Sample Code For Creating Delegates
Suppose you have a function named Add(int x,int y)SampleDelegate.cs


using System;
namespace Delegate
{
public class SampleDelegate
{
public delegate int Sum(int x,int y); //Declaring a Delegate
public static void main(string args[])
{
Sum s= new Sum(Add);//Here the delegate is referring to method Add
s(6,5)//delegate invoked and result will be 11}
public int Add(int x,int y)
{
return x+y;
}//Hope you got a basic idea based on the simple example illustrated above.
}
}


Comments

Author: Phagu Mahato14 Jan 2014 Member Level: Gold   Points : 8

C# delegate is the smarter version of function pointer which helps software architects a lot, specially while utilizing design patterns. a delegate is defined with a specific signature.A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function. Delegates are two types

- Single Cast Delegates
- Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -= .The function will then can be called via the delegate object.

Defining the delegate


public delegate int Exampledelegate (int Num1, int Num2);


Creating methods to delegate object


public int add(int Num1, int Num2)
{
return Num1 + Num2;
}
public int sub( int Num1, int Num2)
{
return Num1 - Num2;
}

3. Creating the delegate object


Myobject mc = new Myobject();
ExampleDelegate add = new ExampleDelegate(mc.add);
ExampleDelegate sub = new ExampleDelegate(mc.sub);


4. Calling the methods via delegate objects

Console.WriteLine("Adding two values: " + add(100, 60));
Console.WriteLine("Subtracting two values: " + sub(100,40));



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: