what is the use of Delegates and why it is use of delegates main reason plz tell me real time example
thanks for advance
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Maroof RainiRank #2,671 · 521 reputationPosted Nov 4, 2013, 5:06 AM EST
For example we have 2 methods as Square and Cube as below-
int Square(int a) //An original Method
{
return a*a;
}
int Cube(int b) // An original Method
{
return a*a*a;
}
delegate int IAmADelegate(int num) /* A delegate, who says that I can represent some method who takes one integer as parameter and returns an integer*/
protected void Page_Load(object sender, EventArgs e)
{
IAmADelegate IMD += new IAmADelegate(Sqaure); /*I am a delegate who will represent Square method so now you can get your task done from me. (Actually I will point your parameter to square method and the method will return its value)*/
Response.Write(IMD(10).ToString()); // Returns 100
Response.Write("
");
IMD += IAmADelegate(Cube);/* Now I am a delegate who will represent Cube method so now you can get your task done from me. (Actually this time I will point your parameter to cube method to get the cube) --- See my skill here, now I am representing Cube means I can represent any method who takes one integer and returns an integer, this is why I am used happily */
Response.Write(a(10).ToString());// Returns 1000
}
In below example its delegate who actually points the method which needs to be executed on click of the button as end with "Handles button click"
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
sureshkumar sp12 reputationPosted Nov 4, 2013, 10:58 PM EST
Best understand of Delegates is can like, in OOPS methodology we can use the value of the member variables in bi-direction right, only can call the member function and get the result. If you want to define a method definition from out side the object or allow the people to change your method definition, delegates support for that.
By delegates we can pass method as parameter to a function or to any instance.
Keyword : delegate
: [Access Modifier] delegate return type DelegateName( [arguments])
Find the attachment to for more your reference.