Fun with delegates
Can a method be passed as a parameter to another method in C#? Sure… Why not…
Part One (basics):
The official definition of delegate is: A delegate is pointer to a function. Nice and simple description. You can view it as a blueprint for a function that you intend to pass. The return type, and parameters of a function and delegate which points to that function, must be the same. Sounds a wee bit confusing. Take a look at the picture bellow:
We have a delegate called TheDelegate that returns nothing and takes no parameters. Then we have TargetFunction() that takes our delegate as a parameter. Well, it can take any method that has the same declaration as TheDelegate. Finally, we made a ParameterFunction() that has required identical declaration as our delegate, and we passed it as a parameter. When you run this, “Yellow World” will be printed out.
Check the picture bellow. I’ll be using this from now on to keep he code cleaner:
Now let’s make a few modifications. Suppose we don’t want to hardcode “Yellow World”, but we want to print an incoming string:
So, the delegate declaration is changed to accept a string parameter. TargetFunction must take method, and parameter for it separetly. Such is the syntax. You can also pass an anonymous function on the spot. For those unfamiliar with what an anonymous function is:
So we can even avoid declaring ParameterFunction, and write everything like this:
Delegates can return values as well:
This will print “Hello” plus whatever the user entered.
.Net already has two types of delegates built in, so you don’t have to declare one yourself. One is called Action<T> the other is Func<T, TResult>, where T is parameter and TResult is return type. Action is used for delegates with void return type, while Func returns something (TResult).
Here is the basic setup:
If you’re confused by this Test3() method, I’m getting to it.
Part Two (method fields)
When we create a class, we usually make something like this:
Imagine if we could make this CheckAgeConstraint… uhm… gettable and settable, just like any field in a class, so you can change what is acceptable on the fly. I’m not saying that this is a good idea, I’m just saying that it is possible.
So, we are making software for human trafficking organization ( work for those who pay the most), and we need to find a way to check and store humans that are suitable for child labour. Between 6 and 14 years old. Lets modify the class:
Now to use it:
So there… You can make… delegated properties so to speak, that can change object’s method behaviour. All of this is also applicable to both Action<T> or pure delegate. How are you gonna use it, is up to you.