I`m having some trouble in understanding how delegates in C# work. I have many code examples, but i still could not grasp it properly.
Can someone explain it to me i
Delegates are reference type, a delegate refers to a method. This is called encapsulating the method. When you create a delegate you specify a method signature and return type. You can encapsulate any matching method with that delegate. You create a delegate with the delegate keyword, followed by a return type and the signatures of the methods that can be delegated to it, as in the following:
public delegate void HelloFunctionDelegate(string message);
class Program
{
static void Main()
{
HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
del("Hello from Delegate");
}
public static void Hello(string strMessage)
{
Console.WriteLine(strMessage);
}
}
Output is Hello from Delegate