Clear, practical technology insights About · Contact

Delegate in C #: Tips and Examples

Understand Delegate in C # with clear explanations, practical examples, and useful tips. This updated guide covers the essential concepts and common mistakes.

Published: 7 minutes read
Table of Contents

Delegate in C # is easier to understand when the core ideas are paired with practical examples. The sections below explain the topic clearly, highlight useful steps, and point out details that can prevent common errors.

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 help 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.

As an example,, consider delegate following:

 public delegate int MyDelegate ( string s ); 

The above delegate can help 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. As an example,:

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

the example below 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 help 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 example below 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 example below will illustrate how to use delegates in C #. The delegate with the name printString can help 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 (); } } } 

Frequently Asked Questions

What should you know about 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.

What should you know about 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.

What should you know about 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 help remove a delegate from a combined delegate.

Was this article helpful?

Your feedback helps us improve.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.