Introduction
In this tutorial, learn what a delegate is in C# and how delegates are implemented in C#. A delegate in C# is a type that is used to invoke a method. In this tutorial, you will learn the following.
- What is a delegate in C#?
- Why do we need delegates in C#?
- What are the benefits of delegates in C# and .NET?
- What are the different types of delegates in C#?
- How are delegates related to events in C#?
- What are single-cast and multicast delegates in C#?
- What is an anonymous delegate in C#?
- C# Delegate code examples
What is a Delegate in C#?
Delegate is one of the base types in .NET. Delegate is a class used to create and invoke delegates at runtime.
A delegate in C# is similar to a function pointer in C or C++. It's a new type of object in C#. A delegate is a very special type of object, as mentioned earlier. The entire object we used to define contained data, but a delegate contains the details of a method.
Why do we need delegates in C#?
C# programmers often need to pass a method as a parameter of other methods when dealing with events. For this purpose, we create and use delegates in C#. A delegate is a class that encapsulates a method signature. Although it can be used in any context, it often serves as the basis for the event-handling model in C# and .NET. One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.
Example
public delegate int DelegateMethod(int x, int y);
Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.
This makes it possible to programmatically change method calls and plug new code into existing classes. You can assign your own delegated method if you know the delegate's signature.
This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.
Why do we need a Delegate?
In class, we create its object, which is an instance, but in delegate, when we create an instance, that is also referred to as a delegate (which means whatever you do, you will get a delegate).
The delegate does not know or care about the class of the object it references. Any object will do; all that matters is that the method's argument types and return types match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
What are the benefits of delegates?
In simple words, delegates are object-oriented, type-safe, and very secure, as they ensure that the signature of the method being called is correct. Delegates make event handling simple and easy.
What are the types of delegates in C#?
There are two types of delegates in C#, singlecast delegates and multiplecast delegates.
- Singlecast delegate: Singlecast delegate points to a single method at a time. The delegate is assigned to a single method at a time. They are derived from System.Delegate class.
- Multicast Delegate: When a delegate is wrapped with more than one method, that is known as a multicast delegate.
In C#, delegates are multicast, meaning they can point to more than one function at a time. They are derived from System.MulticastDelegate class.
How to define a delegate in C#?
There are three steps in defining and using delegates.
Step 1. Declaration of a Delegate.
To create a delegate, you use the delegate keyword.
[attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);
- The attributes factor can be a normal C# attribute.
- The modifier can be one or an appropriate combination of the following keywords: new, public, private, protected, or internal.
- The ReturnType can be any of the data types we have used. It can also be a type void or the name of a class.
- The Name must be a valid C# name.
Because a delegate is a definition for a method, you must use parentheses, which is required for every method. If this method does not take any argument, leave the parentheses empty.
Example
public delegate void DelegateExample();
The above code is how a delegate with no parameters is defined.
Step 2. Instantiation of Delegate.
DelegateExample d1 = new DelegateExample(Display);
The above code shows how a delegate is initiated.
Step 3. Invocation of Delegate.
d1();
The above code piece invokes a delegate d1().
What is a Singlecast delegate in C#?
A sample code demonstrates how to create and use a singlecast delegate.
using System;
namespace ConsoleApplication5
{
class Program
{
public delegate void delmethod();
public class P
{
public static void display()
{
Console.WriteLine("Hello!");
}
public static void show()
{
Console.WriteLine("Hi!");
}
public void print()
{
Console.WriteLine("Print");
}
}
static void Main(string[] args)
{
// here we have assigned static method show() of class P to delegate delmethod()
delmethod del1 = P.show;
// here we have assigned static method display() of class P to delegate delmethod() using new operator
// you can use both ways to assign the delegate
delmethod del2 = new delmethod(P.display);
P obj = new P();
// here first we have create instance of class P and assigned the method print() to the delegate i.e. delegate with class
delmethod del3 = obj.print;
del1();
del2();
del3();
Console.ReadLine();
}
}
}
What is a Multicast delegate in C#?
A sample code demonstrates how to create and use a multicast delegate.
using System;
namespace delegate_Example4
{
class Program
{
public delegate void delmethod(int x, int y);
public class TestMultipleDelegate
{
public void plus_Method1(int x, int y)
{
Console.Write("You are in plus_Method");
Console.WriteLine(x + y);
}
public void subtract_Method2(int x, int y)
{
Console.Write("You are in subtract_Method");
Console.WriteLine(x - y);
}
}
static void Main(string[] args)
{
TestMultipleDelegate obj = new TestMultipleDelegate();
delmethod del = new delmethod(obj.plus_Method1);
// Here we have multicast
del += new delmethod(obj.subtract_Method2);
// plus_Method1 and subtract_Method2 are called
del(50, 10);
Console.WriteLine();
// Here again we have multicast
del -= new delmethod(obj.plus_Method1);
// Only subtract_Method2 is called
del(20, 10);
Console.ReadLine();
}
}
}
Points to remember about Delegates.
- Delegates are similar to C++ function pointers but are type-safe.
- The delegate gives a name to a method signature.
- Delegates allow methods to be passed as parameters.
- Delegates can be used to define callback methods.
- Delegates can be chained together; for example, multiple methods can be called on a single event.
- C# version 2.0 introduces the concept of Anonymous Methods, which permits code blocks to be passed as parameters in place of a separately defined method.
- Delegate helps in code optimization.
- Usage areas of delegates
The most common example of using delegates is in events.
- They are extensively used in threading
- Delegates are also used for the generic class libraries, which have generic functionality defined.
What are Anonymous Delegates in C#?
You can create a delegate, but there is no need to declare the method associated with it. You do not have to explicitly define a method before using the delegate. Such a method is referred to as anonymous. In other words, if a delegate contains its method definition, it is an anonymous method.
The code is an example of using an anonymous delegate.
using System;
public delegate void Test();
public class Program
{
static int Main()
{
Test Display = delegate()
{
Console.WriteLine("Anonymous Delegate method");
};
Display();
return 0;
}
}
Note. You can also handle events in an anonymous method.
How are Delegates Related to Events in C#?
Events and delegates work together. An event is a reference to a delegate, i.e., when an event is raised, a delegate is called. In C# terms, events are a special form of delegates.
Events play an important part in user interfaces and programming notifications. Events and delegates work hand-in-hand to communicate between codes from one class to another. Events are used when something happens in one class or part of the code and another part needs a notification.
A C# event is a class member that is activated whenever the event it was designed for occurs. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the registered method for the event. The event keyword is a delegate modifier. It must always be used in connection with a delegate.
The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.
How to Use Events and Delegates in C#?
Once an event is declared, it must be associated with one or more event handlers before it can be raised. An event handler is nothing but a method that is called using a delegate. Use the += operator to associate an event with an instance of a delegate that already exists.
Example
obj.MyEvent += new MyDelegate(obj.Display);
An event has the value null if it has no registered listeners.
Although events are mostly used in Windows control programming, they can also be implemented in console, web, and other applications.
Program for creating a custom Singlecast delegate and event.
using System;
namespace delegate_custom
{
class Program
{
public delegate void MyDelegate(int a);
public class XX
{
public event MyDelegate MyEvent;
public void RaiseEvent()
{
MyEvent(20);
Console.WriteLine("Event Raised");
}
public void Display(int x)
{
Console.WriteLine("Display Method {0}", x);
}
}
static void Main(string[] args)
{
XX obj = new XX();
obj.MyEvent += new MyDelegate(obj.Display);
obj.RaiseEvent();
Console.ReadLine();
}
}
}
Program for creating custom multiplecast delegates and events.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace delegate_custom_multicast
{
class Program
{
public delegate void MyDelegate(int a, int b);
public class XX
{
public event MyDelegate MyEvent;
public void RaiseEvent(int a, int b)
{
MyEvent(a, b);
Console.WriteLine("Event Raised");
}
public void Add(int x, int y)
{
Console.WriteLine("Add Method {0}", x + y);
}
public void Subtract(int x, int y)
{
Console.WriteLine("Subtract Method {0}", x - y);
}
}
static void Main(string[] args)
{
XX obj = new XX();
obj.MyEvent += new MyDelegate(obj.Add);
obj.MyEvent += new MyDelegate(obj.Subtract);
obj.RaiseEvent(20, 10);
Console.ReadLine();
}
}
}
Conclusion
I hope the article has helped you understand delegates and events.
You may want to read another article on Delegates and Events: Mastering Delegates and Events In C# .NET (c-sharpcorner.com).