Friday, January 20, 2023
HomeITLearn how to work with delegates in C#

Learn how to work with delegates in C#


A delegate is a kind that references a way that has the identical signature as that of the delegate. In different phrases, delegates are used to move strategies as arguments to different strategies. You’ll be able to make the most of delegates in C# to implement occasion handlers and callback strategies. A multicast delegate is one that may level to a number of strategies which have equivalent signatures.

Understanding delegates in C#

Delegates in C# are much like operate pointers in C or C++, however delegates are type-safe. That’s, delegates are type-safe references that time to a number of strategies which have signatures equivalent to that of the delegate. We’ll see the best way to use multicast delegates to reference a number of strategies later on this article.

You’ll be able to declare a delegate that stands by itself or that’s nested inside a category. You’ll be able to move strategies as parameters to a delegate to permit the delegate to level to the strategy. And you’ll invoke the strategy by calling the delegate occasion.

First you will need to create a way that the delegate will level to. We’ll use the next technique in our instance.

 void ShowText(string str)
   {
      Console.WriteLine(str);
   }

As soon as we’ve got a way, there are three steps in utilizing delegates: declaration, instantiation, and invocation. The signature of a delegate is proven under.

delegate result-type identifier ([parameters])

You’ll be able to declare a delegate as proven within the following assertion. 

public delegate void MyDelegate(string textual content);

The delegate declared above has the identify MyDelegate, has a return kind of void, and accepts a string object as an argument. The delegate MyDelegate can level to any technique that has an equivalent signature, i.e., any technique that has the identical argument checklist and return kind. Word that the signature of our ShowText technique is strictly the identical because the signature of MyDelegate.

You should instantiate a delegate earlier than you should use it. The assertion under reveals how one can instantiate the delegate declared above.

MyDelegate d = new MyDelegate(ShowText);

Upon getting declared and instantiated the delegate, you possibly can invoke the strategy utilizing the delegate.

d("Hi there World...");

Right here, d is the delegate occasion. It’s also possible to invoke the strategy that the delegate occasion factors to utilizing the Invoke() technique on the delegate occasion.

d.Invoke("Hi there World...");

A delegate instance in C#

Right here is the entire code itemizing for the MyDelegate instance we stepped by way of above.

utilizing System;
namespace Delegates
{
    public delegate void MyDelegate(string textual content);
    class Program
    {
        public static void ShowText(string textual content)
        {
            Console.WriteLine(textual content);
        }
        static void Major()
        {
            MyDelegate d = new MyDelegate(ShowText);
            d("Hi there World...");
            Console.ReadLine();
        }
    }
}

And here’s a second instance. Let’s say you may have a way that accepts two numbers, provides them collectively, and returns the sum. You need to use a delegate to retailer the return worth of the strategy as proven within the code snippet given under.

int end result = d(12, 15);

Right here is the entire code itemizing.

utilizing System;
namespace Delegates
{
    public delegate int MyDelegate(int x, int y);
    class Program
    {
        static int Sum(int x, int y)
        {
            return x + y;
        }
        static void Major()
        {
            MyDelegate d = new MyDelegate(Sum);
            int end result = d.Invoke(12, 15);
            Console.WriteLine(end result);
            Console.ReadLine();
        }
    }
} 

Multicast delegates in C#

Word you can assign a number of delegate objects to a delegate occasion utilizing the + operator. It’s also possible to mix delegate cases utilizing the static technique Mix. A delegate that factors to a number of delegates is named a multicast delegate. 

The runtime maintains an inventory (referred to as an Invocation checklist) to execute a number of strategies. When a multicast delegate is named, the delegates within the checklist are executed so as.

The next code itemizing reveals how you should use the Mix() technique to mix a number of delegate cases.

myDelegate d1 = new myDelegate(Method1);
myDelegate d2 = new myDelegate(Method2);
myDelegate multicastDelegate = (myDelegate)Delegate.Mix(d1, d2);
multicastDelegate.Invoke();

Word that delegate cases are immutable. Everytime you mix delegates, otherwise you subtract a delegate occasion from the checklist, a brand new delegate occasion is created to signify the brand new or up to date checklist of strategies to be invoked.

The next code itemizing illustrates a multicast delegate. Word using the += operator to assign the delegate to a number of strategies which have equivalent signatures.

utilizing System;
namespace Delegates
{
    public delegate void MyDelegate();
    class Program
    {
        public static void Method1()
        {
            Console.WriteLine("Inside Method1...");
        }
        public static void Method2()
        {
            Console.WriteLine("Inside Method2...");
        }
        static void Major()
        {
            MyDelegate d = null;
            d += Method1;
            d += Method2;
            d.Invoke();
            Console.ReadLine();
        }
    }
}

Advantages and disadvantages of delegates in C#

Listed below are a number of advantages of delegates to bear in mind:

  • Delegates can be utilized to invoke static and non-static strategies.
  • A delegate can be utilized to name a number of strategies having equivalent signatures.
  • Delegates can be utilized to outline callback strategies and invoke occasion handlers.
  • Delegates might be mixed into multicast delegates that execute a series of delegates so as.

Listed below are a number of the downsides of utilizing delegates:

  • A delegate will execute extra slowly than a standard technique as a result of the runtime must resolve the strategy reference earlier than the delegate name is resolved and the strategy is named.
  • An exception thrown in a way referenced by a delegate doesn’t present the explanation for the error, which makes debugging tougher.
  • The extra delegates you utilize, the much less readable your code turns into.
  • While you use delegates, the JIT compiler and runtime might optimize far lower than typical capabilities.

Delegates are ideally suited to implementing event-driven programming. A delegate doesn’t must know the category of the article to which it refers. All a delegate must know is the signature of the strategy to which it will level. Correct utilization of delegates can promote reusability in your code and suppleness in your designs. You’ll be able to consult with Microsoft’s on-line documentation to be taught extra about delegates.

Copyright © 2023 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments