What is a delegate?
What is a delegate?
Rating:
A delegate is a type of function pointer used by the .NET Framework. Technically, a delegate is used in function calling, events, and type-safety. The best feature of a delegate is that it does not know about the class of the object that it references at compile-time. The only thing that matters is that the argument(s) and return type of the method must match with the argument(s) and return type of the delegate. The .NET Framework has a System.Delegate namespace to handle delegates.
The following syntax is used to declare a delegate:
The following code snippet displays the use of a delegate:
using System;
delegate void MyFirstDelegate(string str);
class MyFirstDelegateClass
{
public static void Show(string str)
{
Console.WriteLine(" Show, {0}", str);
}
public static void Hide(string str)
{
Console.WriteLine(" Hide, {0}", str);
}
public static void Main()
{
MyFirstDelegate a1,b1;
a1 = new MyFirstDelegate(Show);
b1 = new MyFirstDelegate(Hide);
Console.WriteLine("Call Delegate a:");
a1("Del_A");// call Show()
Console.WriteLine("Call Delegate b:");
b1("Del_B");// call Hide()
}
}
Rating:
Other articles
- What is the RSA algorithm?
- How to use the UTF8Encoding class to encode and decode a text?
- How to draw an icon on picture box control in a Windows application?
- What is the MemoryStream class?
- What is the IEquatable generic interface?