I was working with the Action Delegates in C# in the hope of learning more about them and thinking where they might be useful.
Has anybody used the Action Delegate, and if so why? or could you give some examples where it might be useful?
I was working with the Action Delegates in C# in the hope of learning more about them and thinking where they might be useful.
Has anybody used the Action Delegate, and if so why? or could you give some examples where it might be useful?
MSDN says:
Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value.
I used it as a callback in an event handler. When I raise the event, I pass in a method taking a string a parameter. This is what the raising of the event looks like:
The Method:
The is the class declaration of the event Args:
This way I can call the method passed from the event handler with a some parameter to update the data. I use this to request some information from the user.
I use it when I am dealing with Illegal Cross Thread Calls For example:
I must give credit to Reed Copsey SO user 65358 for the solution. My full question with answers is SO Question 2587930
For an example of how Action<> is used.
Console.WriteLine has a signature that satisifies
Action<string>
.Hope this helps
Here is a small example that shows the usefulness of the Action delegate
Notice that the foreach method iterates the collection of names and executes the
print
method against each member of the collection. This a bit of a paradigm shift for us C# developers as we move towards a more functional style of programming. (For more info on the computer science behind it read this: http://en.wikipedia.org/wiki/Map_(higher-order_function).Now if you are using C# 3 you can slick this up a bit with a lambda expression like so:
We use a lot of Action delegate functionality in tests. When we need to build some default object and later need to modify it. I made little example. To build default person (John Doe) object we use
BuildPerson()
function. Later we add Jane Doe too, but we modify her birthdate and name and height.