Press ESC to close

C# Delegate

The delegation of the dictatorship stands out as a delegate to the Turkish counterpart. In this article we will talk about Delegates used in many projects. First of all, if we want to explain its purpose, we can say that delegates are method holders. Delegates are constructs that can hold the addresses of the methods and therefore the methods themselves. Since the delegates are of reference type, the object can be retrieved.

There are points we need to be aware of when using a delegate. These;

  • The method that holds the return type should be the moment with the return type.
  • The trapping method should be the same as the parameter types.
  • The same number of parameters must be included.

As you can see in the code snippet below, we are doing 4 mathematical operations. What we need to note here is that these 4 functions only take 2 parameters from the outside and return the same type value. We then define a delegate that returns the same type and the same value. If you pay attention to this delegate, I have given you a function or method. That’s why we can call function holders for delegate.

static void Main(string[] args)
        {
            Islemler islemler = new Islemler(Topla);
            int hesap = islemler(300,44);
            Console.WriteLine(hesap);
            Console.ReadKey();

        }

        // Delege oluşturuyoruz
        public delegate int Islemler(int ilkSayi, int ikinciSayi);

        // 4 temel işlemi gerçekleştiriyoruz
        public static int Topla(int a, int b)
        {
            return a + b;
        }
        public static int Cikar (int a,int b)
        {
            return a - b;
        }
        public static int Carp(int a, int b)
        {
            return a * b;
        }
        public static int Bol(int a, int b)
        {
            return a / b;
        }

If you have any questions, please feel free to mail or comment me.

Leave a Reply

Your email address will not be published. Required fields are marked *