Delegates and usage of Delegates


In this artical i'm trying to explain about What is delegates ? usage of delegates ? types of delegates and examples of types of delegates.? 2 types of delegates are available uni cost delegates and multi cost delegates. Here we discuss about uni cost and multi cost delegates with examples.

DELEGATES



A Delegate is a pointer to a method similar to a function pointer concept in our traditional c and cpp languages.

Delegates are used to invoking methods just like we used function pointer for invoking functions. Invoking a method using a delegate will give you faster performance than invoking a method directly because here it uses a single function stack for execution of method any number of times.
Working with delegate's.

To use a delegate we need to fallow this following process.

Syntax:-

[<modifier>] delegate <void/type> <name> (parameter definition);


While declaring a delegate to invoke a method makes sure the I/O parameters of delegate will be same as the I/O parameters of method it wants to call.

Ex1:-


public void add (int x ,int y)
{
Console.WriteLine(x+y);
}

public delegate void addnums (int x ,int y);


Ex2:-

public string some(String str)
{
return "some"+str;
}
public delegate String something(String str);



2) A delegate also a type(return type) so to consume a delegate we need to create object of the delegate and while creating the object pass the method the delegate has to call as a parameter to its constructor.


addnums ad=new addnums(add);
something st=new something(some);



3)Now call the delegate so that the method gets executed.

Example

Class declass
{
Public String sayhay(String name)
{
return "hay "+name;
}

Public delegate String saydel(String name);
Public static void Main()
{
declass dl = new declass();
saydel sd =new saydel(dl.saydel);
Console.WriteLine (sd("xxx"));
Console.WriteLine (sd("yyy"));
Console.WriteLine (sd("zzz"));
Console.ReadLine();
}
}


For calling a method in single time is not useful multiple times are useful because single stack is used then performance is increased.

Types of Delegates:

Delegates are two types.

1)Uni-cost Delegates
2)Multi –cost Delegates

If a delegate is used for invoking a single method it is refused as uni-cost delegate (or) single cost delegate where as if a delegate is used for invoking multiple methods We call it as multi-cost delegates.
If we want to call multiple methods using a single delegate all those method shared have the same I/O parameters. Because I/O parameters of the delegate should always match with I/O parameters of the method we want to call.

Note:- we can declare a delegate either with in the class as well as with in the namespace also.


Public delegate void math(int x,int y);
Class multidel
{
public void add(int x,int y)
{
Console.WriteLine ("Add:"x+y);
}
public void mul(int x,int y)
{
Console.WriteLine ("mul:"x*y);
}
public void sub(int x,int y)
{
Console.WriteLine ("sub:"x-y);
}
public void div(int x,int y)
{
Console.WriteLine ("div:"x/y);
}
Static void main()
{
multidel obj=new multidel();
math m= new math(obj.add);
m+=obj.sub;
m+=obj.div;
m+=obj.mul;
m(100,50);
Console.WriteLine ();
m(50,20);
Console.WriteLine ();
m-=obj.mul;
m(30,90);
Console.ReadLine();
}
}

If multiple methods are bound with a delegate a single delegate call will invoke all the method that are bound to with the delegate.


Article by naveensanagasetti
I hope you enjoyed to read my article, If you have any queries out of this then please post your comments.

Follow naveensanagasetti or read 139 articles authored by naveensanagasetti

Comments

Author: Phagu Mahato05 Sep 2013 Member Level: Gold   Points : 10

Thank Naveen for this resource Delegates and its usage . We can create custom Singlecast delegate and event


using System;



namespace Mydelegatecustom

{

class Program

{

public delegate void YourDelegate(int a);



public class Exa

{

public event YourDelegate Yourevent;



public void MyRaiseEvent()

{

Yourevent(40);

Console.WriteLine("Your Event had Raised");

}



public void Display(int x)

{

Console.WriteLine("My Display Method {0}", x);

}

}



static void Main(string[] args)

{



Exa obj = new Exa();

obj.Yourevent += new YourDelegate(obj.Display);



obj.RaiseEvent();

Console.ReadLine();

}

}


Source code for creating custom Multiplecast delegate and event



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace multicastdelegatecustom

{

class Program

{

public delegate void YourDelegate(int x, int y);



public class Exa

{



public event YourDelegate Yourevent;



public void MyRaiseEvent(int x, int y)

{

Yourevent(x, y);

Console.WriteLine("Your Event had Raised");

}



public void Addition(int p, int q)

{

Console.WriteLine("Adding Method {0}", p + q);

}



public void Subtr(int x, int y)

{

Console.WriteLine("Your Subtract Method {0}", p - q);

}

}



static void Main(string[] args)

{

Exa obj = new Exa();

obj.Yourevent += new YourDelegate(obj.Addition);

obj.Yourevent += new YourDelegate(obj.Subtr);

obj.MyRaiseEvent(30, 10);

Console.ReadLine();

}

}

}

Author: Phagu Mahato07 Sep 2013 Member Level: Gold   Points : 5

We can also use Delegates as Statics Members Because it is kind of clunky that the client has instigate the delegate each time that the delegate is to be used. Like below code snippets.
class DBconnectioan
{
oublic Dbconnecttion (string name)
{
this.name=name;
}
protected string Name ;
public string name
{
get
{
return this.Name
}
set
{
This.Name=value;
}
}
}
classDbManager
{
return this.Name;
set
{
this.Name=value;
}
}
}
static DBconnection[] activeconnecttions;
{
//Looping Statement;
}
}
Compiling and execute this application results in the following output;
Callback method called DBconnection 1
Callback method called DBconnection 2
Callback method called DBconnection 2

Author: Phagu Mahato09 Oct 2013 Member Level: Gold   Points : 7

C# - What is Delegates in C# Example | Use of Delegates in C#
Introduction:

In this example I will explain about what is delegates in c#.net with example. Basically delegates in c# are type safe objects. Delegates concept will match with pointer concept of C/C++ language.

Description:
Delegates are type - safe , secure managed objects. This means that the runtime guarantee that a delegates that a delegates points to valid method.In this example I will be looking at delegates how they compare to interface , Syntax of Delegate & Methods Declaration


Check below Example code for delegate declaration and methods declaration


public delegate int Delegatemethod(int a,int b);

public class Exampleclass
{
public int Addition(int x, int z)
{
return x + z;
}
public int Subtraction(int x, int z)
{
return x + z;
}
}
If you observe above code I declared Delegate method method with two parameters which matching with methods declared in Exampleclass class.

Complete Example


public delegate int DelegatExample(int a,int b);
public class Exampleclass
{
public int Addition(int x, int z)
{
return x + z;
}
public int Subtraction(int x, int z)
{
return x - z;
}
}
class Program
{
static void Main(string[] args)
{
Exampleclass sc=new Exampleclass();

DelegatExample delgate1 = sc.Addition;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatExample delgate2 = sc.Subtraction;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output



  • 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: