C# – How Delegates Work

Coding in C# is always fun, when you come from the VBA Excel world. There is much cool stuff, which you see and then you start wondering – why is this not implemented in VBA and why should I write plenty of code just to achieve it.

Delegates are something like this. Cool stuff in C#.

What delegates do? That’s what MSDN says about it:

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
So in my test file I have two different delegates – the first one is a void and the second one an int. The void delegate is made by the standard way a delegate is made – functions are declared, added and executed. The int delegate is a bit more interesting – we have functions again, but the delegate functions are later set in a list and a foreach loop is used with this list, in order to get the result.
This is the output:
delegate
And this is the code:

Also in GitHub!

Enjoy it! 😀
Tagged with: , ,