Home » .Net

Calling Member Function using delegates in C#

In this article, we will learn how to call a member function using delegates in C#? It is similar to the static member function calling.
Submitted by IncludeHelp, on August 22, 2018

Prerequisite: Delegates in C#

We can also call a member function of a class using delegates. It is similar to static function calls, here we have to pass member function using an object on the creation of delegate.

Program:

using System;
using System.Collections;

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


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

Output

    Call a member function using delegate

In above example, we created the class Sample, Sample class contains a member function name fun(). And then, we created another class Program than contains Main() function. Here, we created delegate reference and passed member function using Sample class object.



Comments and Discussions!

Load comments ↻





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