Delegates with Example in C#

C# delegates with Example: In this article, we will realize what are assigns in C#, how to call a static technique with a representative?

In C#, delegates are utilized to reference a strategy for a class. It’s practically like the capacity pointer in C and C++. Using a representative we can epitomize to a technique for the class inside an object of the agent.

Call a technique without delegate

We can comprehend assigns by giving an example of a capacity call with or without a representative.

using System;
using System.Collections;

class Sample
{
    public void fun()
    {
        Console.WriteLine("Call a Function without delegate");
    }
}

class Program
{
    static void Main()
    {
        Sample S = new Sample();

        S.fun();
    }
}

Output

    Call a Function without delegate

We can call a technique using delegate moreover. Here, we have to utilize the delegate keyword.

Syntax:

 delegate return_type <delegate_name>([perameters]);

Here,

  • return_type – matches return sort of the capacity.
  • delegate_name – is an identifier that is client characterized delegate name.
  • parameters – that characterize parameters went in work.

Call a Static strategy using delegate

using System;
using System.Collections;

public delegate void myDelegates();
class Sample
{
    public static void fun()
    {
        Console.WriteLine("Call a static function using delegate");
    }
}

class Program
{
    static void Main()
    {
        myDelegates del = new myDelegates(Sample.fun);
        del();
    }
}

Output

    Call a static function using delegate

Leave a Comment

error: Alert: Content is protected!!