Delegate in C #

Delegate in C # is similar to pointers to functions, in C or in C ++. Delegate is a reference type variable that contains references to a method. That reference can be changed at runtime.

Delegate in C # is similar to pointers to functions, in C or in C ++.Delegate is a reference type variable that contains references to a method. That reference can be changed at runtime.

In particular, delegates are used to deploy call events and call-back methods. All delegates are implicitly derived from the System.Delegate class in C #.

Declaring the Delegate in C #

Delegate declaration in C # defines the methods that can be referenced by Delegate. A Delegate can refer to a method, which has the same sign as Delegate.

For example, consider delegate following:

 public delegate int MyDelegate ( string s ); 

The above delegate can be used to reference any method that has a single string parameter and returns a variable of type int .

The syntax for declaring delegates in C # is:

 delegate < ki ể u_tr ả _v ề> < t ê n_delegate > < danh_s á ch_tham_s ố> 

Initialize Delegate in C #

When delegate type is declared, delegate object must be created with new keyword and associated with a specific method. When creating a delegate, the parameter passed to the new expression is written similar to a method call, but there is no parameter to that method. For example:

 public delegate void printString ( string s ); . printString ps1 = new printString ( WriteToScreen ); printString ps2 = new printString ( WriteToFile ); 

The following example illustrates how to declare, initialize, and use delegates to reference methods, taking integer parameters and returning an integer value.

 using System ; delegate int NumberChanger ( int n ); namespace DelegateAppl { class TestDelegate { static int num = 10 ; public static int AddNum ( int p ) { num += p ; return num ; } public static int MultNum ( int q ) { num *= q ; return num ; } public static int getNum () { return num ; } static void Main ( string [] args ) { //tạo thể hiện delegate NumberChanger nc1 = new NumberChanger ( AddNum ); NumberChanger nc2 = new NumberChanger ( MultNum ); //gọi phương thức sử dụng đối tượng delegate nc1 ( 25 ); Console . WriteLine ( "Giá trị của số: {0}" , getNum ()); nc2 ( 5 ); Console . WriteLine ( "Giá trị của số: {0}" , getNum ()); Console . ReadKey (); } } } 

When running the above code you will get the following result:

 Value of number: 35 
Value of number: 175

Multicast (multidirectional) a Delegate in C #

Delegate objects can be composed of other delegates with the "+" operator. A delegate is composed of two Delegates that are composed of that word. Only the same type delegates can be formed. The "-" operator can be used to remove a delegate from a combined delegate.

Using this feature of delegates, you can create a summon list of methods that will be called when that delegate is summoned. This is called Multicasting of a Delegate. The following example program illustrates Multicasting of a Delegate in C #:

 using System ; delegate int NumberChanger ( int n ); namespace QTMCSharp { class Tester { static int num = 10 ; public static int AddNum ( int p ) { num += p ; return num ; } public static int MultNum ( int q ) { num *= q ; return num ; } public static int getNum () { return num ; } static void Main ( string [] args ) { //tạo các thể hiện delegate NumberChanger nc ; NumberChanger nc1 = new NumberChanger ( AddNum ); NumberChanger nc2 = new NumberChanger ( MultNum ); nc = nc1 ; nc += nc2 ; //gọi multicast nc ( 5 ); Console . WriteLine ( "Giá trị của số: {0}" , getNum ()); Console . ReadKey (); } } } 

The results when running the above program will be as follows:

 Value of number: 75 

How to use Delegate in C #

The following example will illustrate how to use delegates in C #. The delegate with the name printString can be used to reference the input method as a string and not return anything.

We use this delegate to call two methods: the first method prints the string to Console, and the second method prints it to a File.

 using System ; using System . IO ; namespace QTMCsharp { class TestCsharp { static FileStream fs ; static StreamWriter sw ; // khai báo delegate public delegate void printString ( string s ); // phương thức thứ nhất để in trên console public static void WriteToScreen ( string str ) { Console . WriteLine ( "Chuỗi la: {0}" , str ); } //phương thức thứ hai để ghi dữ liệu vào file public static void WriteToFile ( string s ) { fs = new FileStream ( "c:message.txt" , FileMode . Append , FileAccess . Write ); sw = new StreamWriter ( fs ); sw . WriteLine ( s ); sw . Flush (); sw . Close (); fs . Close (); } // phương thức này nhận delegate làm tham số và // sử dụng nó để gọi các phương thức nếu cần. public static void sendString ( printString ps ) { ps ( "TipsMake.com" ); } static void Main ( string [] args ) { Console . WriteLine ( "Ví dụ về Delegate C#:" ); Console . WriteLine ( "--------------------------" ); printString ps1 = new printString ( WriteToScreen ); printString ps2 = new printString ( WriteToFile ); sendString ( ps1 ); sendString ( ps2 ); Console . ReadKey (); } } } 

Compile and run the C # program to see the results.

 Example of Delegate C #: 
--------------------------
The series is: TipsMake.com

According to Tutorialspoint

Previous article: Indexer in C #

Next article: Events (Event) in C #

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile