Delegates in C#

  • comes under System.delegates
  • type of variable which keeps references to methods
  • defines return type and parameter list

Example:

class Program
{
//declaring delegate
delegate double calc(num1,num2);

public double addition(num1,num2)//same signature
{return num1+num2;}

public double minus(num1,num2)//same signature
{return num1-num2;}
}

class MainClass
{
private static void main(string[] args)
{
calc delObj;//created object with delegate
string input=Console.readLine();
if(input==’Add’)
{
//instantiate delegate with reference to addition
delObj=new delObj(addition);
}
else
{
//instantiate delegate
delObj=new delObj(minus);
}

//call delegate
delObj(10,20)
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s