Skip to main content

Delegates :: Advance : C# programming for c++ programmers


1. Definition: 

A Delegate is a type safe function pointers and it hold reference(i.e. Pointer) to a function. 

  • Delegates are like reference types like classes and interfaces. Unlike structures are value type.
  • The reasont o say delegate as type safe because  delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error.



Syntax:  Same a member function with a keyword delegate


public delegate void func(string param);


class demo
{
    public static void Main()
    {
        // ignature must match the signature of the delegate
        func del = new func(method);

        // Invoke the delegate, which will invoke the method
        del("Hello from Delegte");
    }


    public static void method(string param)
    {
        Console.WriteLine(param);
    }
}


Note:

Compare parameter of the method and delegate parameters and return type. If the parameters don't match then it would lead to the compiler error.


2. Why Delegates:

 Here in below example, the employee is promoted if the salary is greater than 5000, let say if some other organization wants to have a different rule for promotion. In such case reusable, since we have hard coded value, hence it is not flexible.

Example: 

class demo
    {
        public static void main()
        {
            List list_org = new List();
            list_org.Add(new organization() { empId = 101, Name = "iliyas", salary = 5000 });
            list_org.Add(new organization() { empId = 101, Name = "patel", salary = 2000 });
            list_org.Add(new organization() { empId = 101, Name = "kabir", salary = 6000 });

            organization.promoteemp(list_org);
        
        }
    }

    class organization
    {
        public int empId { get; set; }
        public string  Name { get; set; }
        public int salary { get; set; }

        public static bool promoteemp(List list_org)
        {
            foreach (organization orgn in list_org)
            {
                if (orgn.salary >= 5000)
                {
                    Console.WriteLine("Promoted : " + orgn.Name);
                }
            }
        }

    }




With Delegate:

class demo
    {
        public static void main()
        {
            List list_org = new List();
            list_org.Add(new organization() { empId = 101, Name = "iliyas", salary = 5000 });
            list_org.Add(new organization() { empId = 101, Name = "patel", salary = 2000 });
            list_org.Add(new organization() { empId = 101, Name = "kabir", salary = 6000 });

   IsPromotable isPromote = new IsPromotable(Promote);



            organization.promoteemp(list_org, isPromote);
        
        }

public bool Promote(Employee emp)
        {
            if(emp.salary >= 5000)
return true
   else
return false;
        } 
    }
    
    

    delegate bool IsPromotable(List list_org);

    class organization
    {
        public int empId { get; set; }
        public string  Name { get; set; }
        public int salary { get; set; }

        public static bool promoteemp(List list_org, IsPromotable IsEligible)
        {
            foreach (organization orgn in list_org)
            {
                if (IsEligible(orgn))
                {
                    Console.WriteLine("Promoted : " + orgn.Name);
                }
            }
        }

    }






With Delegate using Lambda expression:



class demo
    {
        public static void main()
        {
            List list_org = new List();
            list_org.Add(new organization() { empId = 101, Name = "iliyas", salary = 5000 });
            list_org.Add(new organization() { empId = 101, Name = "patel", salary = 2000 });
            list_org.Add(new organization() { empId = 101, Name = "kabir", salary = 6000 });

   organization.promoteemp(list_org, emp=>emp.salary >= 5000);
        
        }

    }
    
    



    delegate bool IsPromotable(List list_org);

    class organization
    {
        public int empId { get; set; }
        public string  Name { get; set; }
        public int salary { get; set; }

        public static bool promoteemp(List list_org, IsPromotable IsEligible)
        {
            foreach (organization orgn in list_org)
            {
                if (IsEligible(orgn))
                {
                    Console.WriteLine("Promoted : " + orgn.Name);
                }
            }
        }

    }

Comments

Popular posts from this blog

Part1 : STL Algorithms (Non-Modifying sequence) in c++

Non-Modifying sequence operations : 1.  Non-modifying sequence operations:   _of (CPP 11) std::array all_of_elem = { 3,5,7,11,13,17,19,23 }; 1. if ( std::all_of ( all_of_elem.begin(),   all_of_elem.end() ,  [](int i) {return i % 2; } )) std::cout << "All the elements are odd numbers.\n"; std::array any_of_elem = { 0,1,-1,3,-3,5,-5 }; 2. if ( std::any_of ( any_of_elem.begin() ,  any_of_elem.end() ,  [](int i) {return i )) std::cout << "There are negative elements in the range.\n"; std::array foo = { 1,2,4,8,16,32,64,128 }; 3. if ( std::none_of ( foo.begin() ,  foo.end() ,  [](int i) {return i )) std::cout << "There are no negative elements in the range.\n"; 2.  Non-modifying sequence operations:   find       std::string myints[] = { "Hello", "Hi", "Bye", "ByeBye" }; std::vector myvector(myints, myints + 4); std::vector ::iterator it;...

Structured Bindings

Returning multiple Values from function C++ 11 vs C++ 17 Returning compound objects Iterating over a compound collection Direct initialization Returning multiple Values from function C++ 11 vs C++ 17 :  C++ 11 (std::tie): std::tuple mytuple() {     char a = 'a';     int i = 123;     bool b = true;     return std::make_tuple(a, i, b);  // packing variable into tuple } To access return value using C++ 11, we would need something like: char a; int i; bool b; std::tie(a, i, b) = mytuple();  // unpacking tuple into variables Where the variables have to be defined before use and the types known in advance. C++ 17 : auto [a, i, b] = mytuple(); Returning compound objects :  This is the easy way to assign the individual parts of a compound type (such as a struct, pair etc) to different variables all in one go – and have the correct types automatically assigned. So let’s have a look at an ...

Containers in c++

SEQUENTIAL CONTAINER Vector (Dynamic Array - Contiguous memory):  O(1): Vectors provide fast (constant time) element insertion and deletion at the end of the vector and Acess. O(n): Slow (linear time) insertion and deletion anywhere else. Insertion and deletion are slow because the operation must move all the elements “down” or “up” by one to make room for the new element or to fill the space left by the deleted element. Like arrays, vectors provide fast (constant time) access to any of their elements. List (Doubly Linked List - Not  Contiguous memory ): O(n): Lists provide slow (linear time) element lookup and access, O(1):  (constant time) insertion and deletion of elements once the relevant position has been found Deque (Doubly Ended Queue - Not Contiguous memory): O(1): (constant time) element access. Like a list, it provides fast (amortized constant time) insertion and deletion at both ends of the sequence. O(1):  (lin...