Home > Backend Development > C#.Net Tutorial > How to declare and instantiate delegates in C#?

How to declare and instantiate delegates in C#?

WBOY
Release: 2023-09-04 20:01:05
forward
1435 people have browsed it

How to declare and instantiate delegates in C#?

C# A delegate is similar to a function pointer in C or C#. A delegate is a reference type variable that holds a reference to a method. References can be changed at runtime.

Syntax for declaring delegates -

delegate <return type> <delegate-name> <parameter list>
Copy after login

Now let’s see how to instantiate a delegate in C#.

After declaring a delegate type, you must use the new keyword to create a delegate object and associate it with a specific method. When you create a delegate, the parameters passed to the new expression are written like a method call, but without the method's parameters.

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

The following is an example of declaring and instantiating a delegate in C# -

Example

Live Demonstration

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) {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);

         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}
Copy after login

Output

Value of Num: 35
Value of Num: 175
Copy after login

The above is the detailed content of How to declare and instantiate delegates in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template