What is the implementation method of C# delegates?
There are several ways to implement C# delegates, such as:
- Use naming conventions: Define a method and then pass the name of that method as a parameter to the delegate instance.
public delegate void MyDelegate(string message);
public class MyClass
{
public static void PrintMessage(string message)
{
Console.WriteLine(message);
}
public static void Main()
{
MyDelegate myDelegate = PrintMessage;
myDelegate("Hello World");
}
}
- Use an anonymous method: Define an anonymous method directly in the parameter position of the delegate.
public delegate void MyDelegate(string message);
public class MyClass
{
public static void Main()
{
MyDelegate myDelegate = delegate (string message)
{
Console.WriteLine(message);
};
myDelegate("Hello World");
}
}
- Using Lambda expressions: Lambda expressions can be used to more concisely define anonymous methods.
public delegate void MyDelegate(string message);
public class MyClass
{
public static void Main()
{
MyDelegate myDelegate = (message) =>
{
Console.WriteLine(message);
};
myDelegate("Hello World");
}
}
Regardless of the method used, delegation can be used to reference methods and allows for methods to be dynamically replaced at runtime.