This website includes Education Information like a programming language, job interview question, general knowledge.mathematics

Education log

PageNavi Results No.

Ads

Sunday, January 21, 2024

what is delegate in c# with example

 what is delegate in c# with example


A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.


In C#, a delegate is a reference type variable that holds a reference to a method. Delegates are similar to function pointers in C and C++, but they are more secure, type-safe, and object-oriented.



Define delegate In C#:


A C# delegate is an object that represents a method. The C# delegate allows you to treat a method as a value, assigning the method to a variable, passing it to other methods as parameters, adding it to a collection, and so on.


Example delegate in c#:


// C# program to illustrate the use of Delegates

using System;

namespace Delegates {

// declare class "Delegates"

class Geeks {

// Declaring the delegates

// Here return type and parameter type should 

// be same as the return type and parameter type

// of the two methods

// "addnum" and "subnum" are two delegate names

public delegate void addnum(int a, int b);

public delegate void subnum(int a, int b);

// method "sum"

public void sum(int a, int b)

{

Console.WriteLine("(100 + 40) = {0}", a + b);

}


// method "subtract"

public void subtract(int a, int b)

{

Console.WriteLine("(100 - 60) = {0}", a - b);

}


// Main Method

public static void Main(String []args)

{

// creating object "obj" of class "Delegates"

Delegates obj = new Delegates();


// creating object of delegate, name as "del_obj1" 

// for method "sum" and "del_obj2" for method "subtract" &

// pass the parameter as the two methods by class object "obj"

// instantiating the delegates

addnum del_obj1 = new addnum(obj.sum);

subnum del_obj2 = new subnum(obj.subtract);


// pass the values to the methods by delegate object

del_obj1(100, 40);

del_obj2(100, 60);


// These can be written as using

// "Invoke" method

// del_obj1.Invoke(100, 40);

// del_obj2.Invoke(100, 60);

}

}

}


No comments:

Post a Comment