Definition:
Basically delegate is list of the methods with
same parameter
Use:
When you have many method and you want to call all method
at same time with same parameter then delegate is use . Delegate is use when method takes same parameter as argument
and also returns same data type value.
Example:
here in example there is two methods name ‘method1’
and ‘method2’ these both method take same argument and dose not return any
value.
How to declare:
For use delegate keyword delegate is used first you have to declare
the delegate like
delegate void Mydelegate(string mystring);
This delegate which return type is void and take ne argument
as string an delegate name is “Mydelegate”
How To Use :
For use this delegate we make instance of that delegate and pass any one method name as argument and
then other method name pass like below code and then pass argument for the method.
Mydelegate md = new Mydelegate(method1);
md += method2;
md("aaaaaaaa");
Complete Code:
using System;
using
System.Collections.Generic;
using
System.ComponentModel;
using System.Data;
using
System.Drawing;
using System.Linq;
using System.Text;
using
System.Windows.Forms;
namespace Delegate
{
public partial class Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
delegate
void Mydelegate(string mystring);
private
void button1_Click(object
sender, EventArgs e)
{
Mydelegate
md = new Mydelegate(method1);
md += method2;
md("aaaaaaaa");
}
void
method1(string a1)
{
MessageBox.Show(a1);
}
void
method2(string a2)
{
MessageBox.Show(a2,
"test");
}
}
}
---------------------------------------------------------------------------------
(b) (h)
ReplyDelete