Home » .Net

Delegates with Example in C#

C# delegates with Example: In this article, we are going to learn what are delegates in C#, how to call a static method with a delegate?
Submitted by IncludeHelp, on August 19, 2018

In C#, delegates are used to reference a method of a class. It’s almost similar to the function pointer in C and C++. Using a delegate we can encapsulate to a method of the class inside an object of the delegate.

We can understand delegates by giving an example of a function call with or without a delegate.

Call a method without delegate

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

Call a method using delegate

We can call a method using delegate also. Here, we need to use delegate keyword.

Syntax:

 delegate return_type <delegate_name>([perameters]);

Here,

  • return_type - matches return type of the function.
  • delegate_name - is an identifier that is user-defined delegate name.
  • parameters - that define parameters passed in function.

Call a Static method 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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.