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
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.