C# Delegates

Before learning a new subject, I often ask myself some questions to improve my learning process. So, let’s start questioning together??

What does C# delegate mean?

Reference types let us manipulate objects by using small references instead of writing the whole object every time we need. For instance, “String”, “Arrays” and “Classes” are reference type data types. A delegate is also a reference type that holds the memory address of a method.

(A method is a block of code which might take parameters and might return a value and performs actions.)

When can I use C# delegates?

When you need to call a series of methods, you can use a single delegate to call a series of methods, or you can call two methods the same in signature using delegate. Another use of delegate is that you can pass methods as arguments to other methods.

How to Declare a delegate?

// MyCustomDelegate does not return any value
public delegate void MyCustomDelegate();

// MyCustomDelegate2 returns an integer
private delegate int MyCustomDelegate2(string newString);        

I created a method and a delegate to calculate the sum of two numbers in the code below:



class Progra
    {
    
    //This delegate returns nothing but takes two parameters.
      public delegate void ThisDelegateAddTwoNumbers(int firstNumber, int secondNumber);
      
      // Main method
      static void Main(string[] args)
      {
          //Set target method
          ThisDelegateAddTwoNumbers additionDelegate = Addition;
          
          //There are two ways to invoke a delegate.
           additionDelegate(9, 9);
          // addition.Invoke(9,9)
          
      }
              
        
     // This method adds two numbers and returns nothing but prints the result. 
     public static void Addition(int firstNumber, int secondNumber)
      {
          Console.WriteLine($"{firstNumber} + {secondNumber}: {firstNumber + secondNumber}");
      }
      
}        

Like other reference types and primitive types, we can pass delegate as a parameter. We can also set new targets using +=(-=) just like we do when we concatenate multiple strings using +=(-=). Let’s analyze delegates together in the code below!


class Progra
    {
      // Main method
      static void Main(string[] args)
      {
          
          ThisIsADelegate firstDelegate = ThisMethodReturnsAString;// Set a target
          ThisIsADelegate secondDelegate = ThisMethodAlsoReturnsAString;// Set a target

        // Output: 1.Hello 2.World
          string concatTwoStringsByCallingDelegates = firstDelegate("Hello") + " " + secondDelegate.Invoke("World");
          Console.WriteLine(concatTwoStringsByCallingDelegates);

        // The last assigned target method's value will be returned
           ThisIsADelegate tryToConcatTwoStrings = firstDelegate;
           tryToConcatTwoStrings += secondDelegate;
           
        // Output: 2.Hello
           Console.WriteLine(tryToConcatTwoStrings.Invoke("Hello"));
          
      }
      // This delegate returns a string and takes a string as a parameter.
      public delegate string ThisIsADelegate(string message);
      
      // This method returns given string.
      public static string ThisMethodReturnsAString(string message)
      {
          return "1." + message;
      }
      // This method also returns given string.
      public static string ThisMethodAlsoReturnsAString(string message)
      {
          return "2." + message;
      }                   
}        

Func Delegate and Action

Did it bother you to define delegates manually every time? Now, it’s time to learn c# Func delegate that saves us from repetitive manual works. Func is a genereic delegate.

Func<input_parameter,output_parameter>
Func<int,int>  //---> output_parameter: int
Func<string,int,bool>  //---> output_parameter: boolean        

If a delegate does not return any value, you can use action instead of Func.

action<int> // ---> input_parameter: int        

Let’s write the same code using Func:)

class Program
    {
      // Main method
      static void Main(string[] args)
      {
           // Outout: 1.Hello
          Func<string, string> firstDelegate = ThisMethodReturnsAString;// set a target
          Console.WriteLine(firstDelegate("Hello"));
          
          // Outout: 2.Hello
          firstDelegate += ThisMethodAlsoReturnsAString;
          Console.WriteLine(firstDelegate("Hello"));
          
      }
      
      // This method returns given string.
      public static string ThisMethodReturnsAString(string message)
      {
          return "1." + message;
      }
      // This method also returns given string.
      public static string ThisMethodAlsoReturnsAString(string message)
      {
          return "2." + message;
      }                   
}        


要查看或添加评论,请登录

ramin azadi的更多文章

  • Constant vs Readonly in C#

    Constant vs Readonly in C#

    Difference Between Const and ReadOnly. One of the most important concepts that we commonly use while writing a C# code .

  • How To Read Data From An Excel Sheet

    How To Read Data From An Excel Sheet

    Step 1 Open Visual studio -> New Project -> Console App. Project Name/App Name.

  • C# Dependency Injection — Service Lifetimes

    C# Dependency Injection — Service Lifetimes

    What is Dependency Injection? ASP.NET Core supports the dependency injection (DI) software design pattern, which is a…

  • Thread vs Task in C#

    Thread vs Task in C#

    Thread in C# The Thread class creates an actual operating system level thread in C#. The thread created with the Thread…

  • Var vs Dynamic in C#

    Var vs Dynamic in C#

    Difference between Var and Dynamic. While writing code in C# we have used Var and Dynamic keyword many times but it is…

社区洞察

其他会员也浏览了