I’ve been little busy these days due to an university research. However, I found some time to return with blog activities. Today, I’ll talk about two easy features of C#: Delegates and Function Pointers.
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, if you are familiar with function pointers, delegates will not be a problem to you at all.
To create a delegate function you just need to declare it in the method signature and do not implement the method body. For example:
To use the delegate you must assign it to a static method, as the example below:
Due to this feature, if I need to create a new currency converter, all I have to do you is to create a new static function that makes the work for me and use it as my delegate method.
Here is where I create my static functions:
And here is where I use them:
A similar approach is using function pointers as a method parameter. To do that we first have to change our convert method by removing the delegate primitive, adding the function pointer parameter and implementing the method body.
And finally, change our program to call the function Convert of PriceConverter class.
Besides of the possibility of resolving this problem with a simple method call, I used delegates and function pointer just to ilustrate the used of them. There’re really a nice feature to avoid switch-cases and bad reuse code implementations. Try to use them.