Delegates in C#.Net

delegates in c sharp

This C#.net tutorial explains, what are delegates in C#.Net? How to call a method using a delegate? We will also discuss how to define a delegate? How to instantiate a delegate in C#.net? How to call a delegate in C#.Net? Also, we will check the multicast delegate? And anonymous methods in C#.net?

Delegates in c sharp

Delegate is a type-safe function pointer. Delegates hold the reference of method and call the method for execution. Delegate is holding the reference of a variable. Delegates are implicitly derived from System.Delegate class.

Delegates allow you to create a variable that points to a method. Then use this variable at any time to invoke the method.

First define the signeture like the method must have the same return type, the same number of parameters, and the same data type for each parameter as the delegate.

A delegate variable can point only to a method that matches its specific signature. The method must have the same return type, the same number of parameters, and the same data type for each parameter as the delegate.

In the C# we can call the method in 3 ways

  1. The static method we can call by name
  2. The Non-static method we need to create the instance
  3. Call the method by using delegate

Static Method:

In the Static method, we can call the method by its name directly no need to create an instance for the class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        public static int totalPrice(int price,int quantity)
        {
           int totalcost=price * quantity;
           return totalcost;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("The total Price is" + totalPrice(1000, 2));
        }   
    }
}
delegates in c sharp
c# delegate example

Nonstatic method: In the non-ststic method we need to create an instance for calling the method. See the below example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    class Program
    {
        public int totalPrice(int price,int quantity)
        {
           int totalcost=price * quantity;
           return totalcost;
        }
        static void Main(string[] args)
        {
            Program prgm = new Program();
            int totalcost=prgm.totalPrice(1000, 2);
            Console.WriteLine(totalcost);
        }   
    }
}
c# .net delegate example
c# .net delegate example

How to Call a method using a Delegate in C#?

Now we will see how to call a method by using delegates. For calling the method through delegate we need to follow below 3 steps.

  1. How to define a delegate
  2. How to instantiating delegates
  3. How to call the delegates

How to defines a Delegate in C#?

Defining a delegate in C#.Net is very easy, it is almost similar to define the method.

<access modifier> delegate Keyword <return type> <delegate name>(<parameters>

Example:

public void totalPrice(int price,int quantity)//method name
public delegate void totalPriceDeligates(int pr, int qn);//deligate define
public static string aboutTsinfo(string strtxt)//method name
public delegate string abtTsinfoDeligate(string text)//deligate name

The difference between the method name and delegate name is we just need to add the delegate keyword in the delegate. We should remember the method name and delegate name should be different but the return type of both method and delegate should be the same. The parameter of both method and delegate should have the same type.

Example. If the method has 2 parameters of int type then delegate should have same. method name variable name we can change but type should not. In the method, name semicolon is not required but in the delegate, name semicolon is required.

How to instantiating delegate in C Sharp?

Instant delegates mean we need to create an instance for the delegate. We can create the instance by following syntax delegate name variablename=new delegate name(pass the method name.)

Below method is a static method so I have created an instance. and in the delegation instance, I have passed the variable name. method name.

Program prgObj = new Program();
 totalPriceDeligates tp= new totalPriceDeligates(prgObj.totalPrice);

if the method is non static we can directly pass the method name in the deligate instance.

abtTsinfoDeligate tx = new abtTsinfoDeligate(aboutTsinfo);

How to call the delegates in C#.Net?

Calling deligate also very easy. We just need to pass the value inside the call function.

tp(1000, 60);
Console.WriteLine(tx(" devlopement company"));

Example-1: The entire code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileIO
{
    public delegate void totalPriceDeligates(int pr, int qn);
    public delegate string abtTsinfoDeligate(string text);

    class Program
    {
        public void totalPrice(int price,int quantity)
        {
            Console.WriteLine(price*quantity);
        }
        public static string aboutTsinfo(string strtxt)
        {
            return "Tsinfo is a good" + strtxt;
        }
        static void Main(string[] args)
        {
            Program prgObj = new Program();
            totalPriceDeligates tp= new totalPriceDeligates(prgObj.totalPrice);
            tp(1000, 60);
            abtTsinfoDeligate tx = new abtTsinfoDeligate(aboutTsinfo);
            Console.WriteLine(tx(" devlopement company"));
        }
    }
}

The output screen will look like below.

c# .net delegation example
c# .net delegation example

MultiCast delegate in C Sharp

When a delegate is going to hold the reference of more than one method we called as Multicast delegates. Previously we were discussed about single cast delegate which will hold the reference of a single method. The Single cast delegate derived from the System. Delegate Class and the multicast delegate derived from System.MulticastDeligate class.

Multicast delegate example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileIO
{
    public delegate void delegateConvert(int x);
    class MulticastDeligate
    {
       
        public void kmToM(int x)
        {
            Console.WriteLine("The conversion of kilometer to meter is " +x * 1000);
        }
        public void kmToCm(int x)
        {
            Console.WriteLine("The conversion of kilometer to centimeter is "+x * 100000);
        }
        static void Main(string[] args)
        {
            MulticastDeligate multicastDeligate = new MulticastDeligate();
            delegateConvert delobj = new delegateConvert(multicastDeligate.kmToM);
            delegateConvert delegateobj = new delegateConvert(multicastDeligate.kmToCm);
            delobj(8);
            delegateobj(10);
            Console.WriteLine();
            delobj(10);
            delegateobj(20);
            Console.WriteLine();
            delobj(12);
            delegateobj(12);

        }
    }
}

The output screen will look like below.

multicast delegates in c# with example program
multicast delegates in c# with example program

Example of C#.net Delegation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileIO
{
    public delegate void delegateTsinfo(string aboutTsinfo);
    class DeligateExam2
    {
        static void abtTs(string txt)
        {
           Console.WriteLine(txt);
        }
        static void aboutTsinfo(string tsinfo)
        {
            Console.WriteLine(tsinfo);
        }
        
        static void Main(string[] args)
        {
            DeligateExam2 obj = new DeligateExam2();
            delegateTsinfo objdeligate = new delegateTsinfo(abtTs);
            objdeligate("SharePoint professionals will help you to build a unique SharePoint portal for your Organization");
            Console.WriteLine();
            delegateTsinfo objdeligatenew = new delegateTsinfo(aboutTsinfo);
            objdeligatenew("We are a startup founded in 1st quarter of 2018 and providing Microsoft SharePoint consulting services to various organization");
      }
    }
}
c#.net delegate example
c#.net delegate example

Anonymous Methods in C#.Net

The anonymous method does not have a method name but it allows the user to pass the block of code. The Anonymous method can define using the delegate keyword.

Previously while creating the instance of the variable we have passes the method name as a parameter for example

delegateConvert delobj = new delegateConvert(multicastDeligate.kmToM);

Now we will see in the Anonymous type how we instantiating the delegate. The anonymous method syntax is

accessmodifier delegatekeyword void deligateName(parameter);
{
deligateName objectdelegate=delegate keyword(parameter)
{
int variable=objectdelegate(100);
}

The Anonymous feature are

  1. It will reduce code complexity.
  2. It will increase the code readability and reduce the complexity of the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileIO
{
    public delegate int DelegateArea(int height, int width);
   
    class Anonymous { 
        static void Main(string[] args)
        {
            Anonymous obj = new Anonymous();
            DelegateArea objdelegate = delegate (int h, int w)

              {
                  return (h*w);
              };
            int sum = objdelegate(10, 20);
            Console.WriteLine("The area of rectangle is "+ sum);            
        }
    }
}
anonymous type c#
anonymous type c#

You may like following C#.Net tutorials:

Conclusion

In the above C#.Net article, we were discussed what is C#.Net delegation? Why it is used? We were also learned what is multicasting deligation and Anonymous method in C#.net?

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →