Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate Array in C#

I am experimenting with calling delegate functions from a delegate array. I've been able to create the array of delegates, but how do I call the delegate?

public delegate void pd();

public static class MyClass
{

    static void p1()
    {
        //...
    }

    static void p2 ()
    {
        //...
    }

    //...

    static pd[] delegates = new pd[] {

        new pd( MyClass.p1 ),
        new pd( MyClass.p2)
        /* ... */
    };
}

public class MainClass
{
    static void Main()
    {
        // Call pd[0]
        // Call pd[1]
    }
}

EDIT: The reason for the array is that I need to call the delegate functions by an index as needed. They are not run in response to an event. I see a critical (stupid) error in my code as I had tried to execute the delegate function using the pd[] type rather than the name of the array (delegates).

like image 961
pro3carp3 Avatar asked Oct 31 '08 22:10

pro3carp3


People also ask

What is the use of delegate in C sharp?

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

What is delegate in C# Corner?

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.

Can we pass delegate as parameter?

Because the instantiated delegate is an object, it can be passed as an argument, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time.

CAN is delegate declared within class?

Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.


2 Answers

If they're all the same type, why not just combine them into a single multicast delegate?

static pd delegateInstance = new pd(MyClass.p1) + new pd(MyClass.p2) ...;

...
pd();
like image 65
Jon Skeet Avatar answered Oct 14 '22 18:10

Jon Skeet


public class MainClass
{
    static void Main()
    {
        pd[0]();
        pd[1]();
    }
}
like image 43
Romain Verdier Avatar answered Oct 14 '22 18:10

Romain Verdier