So I read MSDN and Stack Overflow. I understand what the Action Delegate does in general but it is not clicking no matter how many examples I do. In general, the same goes for the idea of delegates. So here is my question. When you have a function like this:
public GetCustomers(Action<IEnumerable<Customer>,Exception> callBack)
{
}
What is this, and what should I pass to it?
They confused the hell out of me until I read:
That second book is about java, and doesn't mention delegates, but it explains well a problem delegates help solve: communication between classes.
A delegate is a class that points to one or more functions. A delegate instance can be invoked, which will call the function(s) that it points to.
In your case, the
GetCustomers
function takes a second function as a parameter.The second function must take two parameters of type
IEnumerable<Customer>
andException
.To call
GetCustomers
, you need to make a second function for it to call, then pass it a delegate containing the second function.For example:
This call creates a new delegate instance that points to the
GetCustomersCallback
function, and passes that delegate to theGetCustomers
function.GetCustomers
will presumably call the callback after the customers finish loading, and will pass the loaded customers as a parameter.You can also leave out the delegate instantiation and pass the function directly:
it expects a function that takes IEnumerable and Exception and returns void.
btw, GetCustomers seems like a terrible name for this function -- it's asking for an action, so its more like DoSomethingToCustomers
EDIT in response to comment
Well, what's happening here is the caller can specify some action. Suppose GetCustomers is implemented like this:
then you could call Getcustomers from somewhere on a commandline program, and pass it
while you could call GetCustomers from a remote application, for example, and pass it
Also, Slak's comment suggests another reason for delegate parameter -- GetCustomers does retrieve the customers, but asynchronously. Whenever it is done retrieving the customers, it calls the function you give it with either the customerlist or an exception, if an exception occurred.
Simply? Function pointers
Refer link for details on DotNet delegates and events: http://www.codeproject.com/KB/cs/Delegate_To_Event_in_CS.aspx
You would pass it a void method that takes an IEnumerable and an Exception as parameters...
Say you have this method:
You would call the GetCustomers method like this: