Tags
It is commonly known that a C# delegate is very similar to a C++ function pointer.
Compare the next examples in both of the languages:
In C# | In C++ |
// declare the delegate type: delegate void MyDelegate(); // some compatible function: void SomeFunction() { Console.WriteLine("Hello, world!"); } . . . . . // declare and initialise a delegate variable: MyDelegate myVariable = SomeFunction; // call the pointed function: myVariable(); // |
// declare the function pointer type: typedef void (*MyFunctionPointer)(); // some compatible function: void SomeFunction() { cout << "Hello, world!" << endl; } . . . . . // declare and initialise a function pointer: MyFunctionPointer myVariable = &SomeFunction; // call the pointed function: myVariable(); // |
So, they appear analogous.
However there is a noteworthy difference. While in C++ a function pointer only holds a single target function, in C# a delegate variable can be “filled” with more than one function. The operator “+=” allows it. For example:
myVariable += AnotherFunction1; myVariable += AnotherFunction2;
Then, when you invoke it with
myVariable();
the system will call all of the attached functions sequentially.
To “detach” a function, use the “-=” operator. The remove all, execute myVariable = null. To remove all and replace with one, execute myVariable = SomeFunction.
Therefore, a C# delegate is like a list of function pointers.
The same things can be said about Action and Func generic delegates: both can target more than one function.
(There are more differences between delegates and function pointers, which are not the subject of present article).