Skip to main content

Delegates in .NET

What is a delegate?
Microsoft framework exposes callback functionality via delegates. Call back functions are used in various application like Microsoft Windows software, OPC subscriptions in Industrial Automation software's, for providing real time data for web applications, menus, file system changes, exception handling etc.  Delegates can call multiple methods in order wise.
 A delegate object is a wrapper around a method and an object to operate on. All Delegates types are derived from System.Multicastdelegate. Delegate supports the calling of both static and instance methods and callback method is type safe.
How to use it?
class TempretureSensor
{
        // Subscribers to the tempreture sensor instance
        public List<int> subscribers = new List<int>();
        //Define a sensor data type
        public delegate void TemperatureFeedback(int unitId, double value, string tempunit);        
        public void ProcessSubscribers(TemperatureFeedback fd)
        {
            foreach(var item in subscribers)
            {
                if(fd != null)
                {
                    //if any subscribers are present, call them
                    // Assuming plant 1 has id as 1
                    if(item==1)
                        fd(1, 32.5, "degree centigrade");
                    else if(item==2)
                        fd(2, 20.5, "degree centigrade");
                }
            }
        }
  }
//Instance call back example
        void Unit1TempretureFeedback(int unitId, double temp, string tempunit)
        {
            Unit1Temp.Text = temp.ToString() + " " + tempunit;
        }
        //Instance call back example
        private void GetUnit1tempBtn_Click(object sender, EventArgs e)
        {
            TempretureSensor tempSensor = new TempretureSensor();
            tempSensor.subscribers.Add(1);
            // Here we are creating a form instance ans subscribing for feedback
            //Form1 forminstance = new Form1();
            TempretureSensor.TemperatureFeedback tp = null;
            //the += operator is used to append the list referred and tp refers to 
            //the head of the linked list
            tp += new TempretureSensor.TemperatureFeedback(this.Unit1TempretureFeedback);
            tempSensor.ProcessSubscribers(tp);
        }
static void GetTempretureForUnit1(int Id, double temp, string unit)
        {
            if(Id==1)
                tempretures  = "For unit 1 " + temp.ToString() + " " + unit + "\n";
        }
        static void GetTempretureForUnit2(int Id, double temp, string unit)
        {
            if(Id==2)
             tempretures += "For unit 2 " + temp.ToString() + " " + unit;
        }
        /// <summary>
        /// Get for all the subscribers. this example shows how delegates can be called as static instance
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AllUnitTemp_Click(object sender, EventArgs e)
        {
            TempretureSensor globalTempSensor = new TempretureSensor();            
            TempretureSensor.TemperatureFeedback tfb = null;
            // Process the items and gives feedback to a static string
            globalTempSensor.subscribers.Add(1);
            tfb += new TempretureSensor.TemperatureFeedback(Form1.GetTempretureForUnit1);
            globalTempSensor.subscribers.Add(2);
            tfb += new TempretureSensor.TemperatureFeedback(Form1.GetTempretureForUnit2);
            globalTempSensor.ProcessSubscribers(tfb);
            MessageBox.Show(tempretures);
        }

Explaining Delegate 
Each delegate declared has four methods as follows:

  • Constructor
  • Invoke
  • Begin Invoke
  • End Invoke

Delegate has a constructor that takes two parameters, object reference and an integer referring to the callback method.
System.Multicastdelegate is derived from System.Delegate and System.Delegate is derived from System.Object. Use of += on delegates leads to chain of delegates which is internally translated to Delegates' Combine method by the compiler. Similarly -= on delegates is translated to Remove method. Thus providing support for delegate chains.
class Standard1
    {
        public int Passpercentage()
        {
            return 70;
        }
    }
class Standard2
    {
        public int Passpercentage()
        {
            return 80;
        }
    }
namespace DelegateChain
{
    public partial class Form1 : Form
    {
        delegate int GetClassResult();
        public Form1()
        {
            InitializeComponent();
        }
        private void Btnresultdata_Click(object sender, EventArgs e)
        {
            GetClassResult results = null;
            results += new GetClassResult(new Standard1().Passpercentage);
            results += new GetClassResult(new Standard2().Passpercentage);

            Delegate[] delegatearray = results.GetInvocationList();
            foreach(GetClassResult result in delegatearray )
            {
                listBox1.Items.Add(result());
            }
        }
    }
}
Dynamically use of Delegates
System.Delegate offers methods to create and invoke at run-time using methods:

  • CreateDelegate
  • DynamicInvoke
namespace RuntimeDelegates
{
    public delegate void NameAndClass(string name, string cls);
    public delegate void NameOnly(string name);
    public partial class Form1 : Form
    {       
        public Form1()
        {
            InitializeComponent();
        }
       public void Studentname(string name)
        {
            txtName1.Text = name;
        }
        public void StudentDetails(string name, string cls)
        {
            txtName2.Text = name;
            txtClass.Text = cls;
        }
        private void BtnInvoke_Click(object sender, EventArgs e)
        {
            Delegate del;
            // Create deleagte based on the type chosen
            Type delegatetype = radiobtndel1.Checked ? typeof(NameOnly) : typeof(NameAndClass);
            string methodName = radiobtndel1.Checked ? "Studentname": "StudentDetails";           

            // Creates delegate in the run time
            del = Delegate.CreateDelegate(delegatetype, this, methodName);

            //Invoke the deleagte
            // Arguments to the call back functions
            int argumentLength = radiobtndel1.Checked ? 1 : 2;
            object[] arguments = new object[argumentLength];
            if(del.GetType() == typeof(NameOnly)) 
            {
                arguments[0] = "Harsit";
            }
            else
            {
                arguments[0] = "Harsit";
                arguments[1] = "Class 2";
            }
            del.DynamicInvoke(arguments);
        }
    }
}

Comments

Popular posts from this blog

Real time data to web application using Microsoft Signal R and Razor Pages

Today we are going to learn how to create razor pages and how to send run time value to the razor page using Signal R Create a new .NET core web application Add Signal R library by,  Add Client-Side Library dialog in the project, for Provider select "unpkg" and select the latest version from the drop down For Library, enter @aspnet/signalr@1, Add a new folder to the project named as Hubs The chat hub class inherits from HUb class that manages connections and messaging The send message is called to send the message to all the clients. MyHub.cs file contains the following code using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; //using System.Threading.Tasks; namespace SignalRSample.Hubs {     public class MyHub : Hub     {         public async Task SendMessage(string user, string message)         {       ...

CRUD operation with WCF service and WPF client

 The database restored on local server WCF Service is talking to the database. Used Visual Studio 2019, entity framework 6 for data base operations from the service. The service exposes the following API’s.  The WCF contracts has both synchronous and asynchronous API's The client is in WPF. It has three windows, main window, customer window and order window as follows. The client uses the WCF service for database operations. When customer button is clicked, the customer window is displayed as below. We can perform CRUD operation from it. The customer can be searched based on ID. New customer window The order button launched order window. It has combo box to choose the customer ID. On selecting the ID, the order details are displayed in the data grid as follows. The source code is available in the GIT hub, URL below: https://github.com/SwagatikaGoswami/WPF_WCF_CRUD.git

Online Exam App with .NET Core Web API and Blazor Client

 We will develop an app that can host online exam. It will have the feature to register user, allow the user to log in. Dashboard for creating sample tests.  The code is shared in GIT hub repository https://github.com/ SwagatikaGoswami/ OnlineExamApp.git The database is MySQL database. The server is a WEB API .NET Core service that uses entity framework for DB operations. The client is a web assembly blazor application. The password stored in the database is encrypted. Register window is as follows. It checks for the mandatory fields. The log in page is as follows: The admin dashboard after logging in  The admin dashboard when new test button is clicked. It uses a Blazor component for adding new test samples.