Use of delegate in c#

why use delegate in c#?

C-Sharp Delegates References To Methods Delegates are like C++ function pointers, but delegates are fully object-oriented.

Delegate is used to pass methods as arguments to another methods of an class.


you might also visit: C-Sharp Func Delegate


A delegate is a type, which represents references to methods with a particular parameter list and return type.

Lets take an example to understand delegate, First of all we declare delegate, then assign a variable to delegate and pass this variable as an argument to a method. Delegates are object-oriented and type-safe.

Use of delegate in c#


1). Most important use of delegate is you can pass methods as an parameters to an event or method.

2). you can use delegate for defining callback methods.

3). you can make a chin of delegates like passing different methods to an single event.

4). you can encapsulate both an object instance and a method by using delegates.

Declaring delegate

delegate int Calculate(int a, int b);

Delegate definitions

public class Calc { public int Add(int x, int y) => (x + y); public int Subs(int x, int y) => (x - y); public int Multiply(int x, int y) => (x * y); public int Divide(int x, int y) => (x / y); }

Create Class Object to pass class methods as an argument

Calc c = new Calc();

Delegate variable and passing class method as an argument

Calculate cc = new Calculate(c.Add);

Invoke delegate methods

Console.WriteLine(cc(102, 34));

Complete Program:

using System; namespace SWClass { // delegate Declaration delegate int Calculate(int a, int b); // delegate definition public class Calc { public int Add(int x, int y) => (x + y); public int Subs(int x, int y) => (x - y); public int Multiply(int x, int y) => (x * y); public int Divide(int x, int y) => (x / y); } class Program { static void Main(string[] args) { Calc c = new Calc(); // Delegate variable Calculate cc = new Calculate(c.Add); // Invoke delegate methods Console.WriteLine(cc(102, 34)); cc = new Calculate(c.Subs); Console.WriteLine(cc(102, 34)); cc = new Calculate(c.Multiply); Console.WriteLine(cc(102, 34)); cc = new Calculate(c.Divide); Console.WriteLine(cc(102, 34)); Console.ReadKey(); //Returns 136 68 3468 3 } } }

Why use delegate in c#?


Every dot net developer have a question in mind and almost in every dot net interview same question asked, Hope this short article answered you well.

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories