How to use Delegates in C#?

In this post, we talked about delegates in C# and trying to explain with examples why we use it.

Delegate is a data type that can contain methods as a signature. We can assign a method as a value to a variable has defined as a delegate. These delegates are reference typed. They refer to the methods. Let's define delegate in example:
public delegate void FooDelegate();
In the code above, we defined delegate as a signature. This delegate can just be represented void return typed methods without parameters. It's our first rule. We can't assign int return typed function to object of this delegate. If we want to assign method then it must be match this signature.

So, let's create some functions according to this delegate and use them with delegate:
namespace DelegateConsole
{
    class Program
    {
        public delegate void FooDelegate();
        static FooDelegate fooDelegate;

        static void Main(string[] args)
        {
            fooDelegate += Close;
            fooDelegate += Open;
            fooDelegate();

            fooDelegate -= Close;
            fooDelegate.Invoke();
        }

        public static void Close(){
            Console.WriteLine("Closed");
        }
        
        public static void Open(){
            Console.WriteLine("Opened");
        }    
    }
}
Output this code:
Closed
Opened
Opened
Delegates may not mean anything by themselves. But they are really useful with callbacks, EventHandler and other related things.

No comments:

Post a Comment