I am learning about MVVM so I can support an application that my predecessor developed. I came across this article which has been helpful.
There is a piece of the code in the article that I don’t understand and have been trying to figure out:
_ServiceAgent.GetPeople((s,e) => this.People = e.Result);
Here is the explanation that the author gives:
a call to GetPeople is made which invokes a method on the service agent and
passes a callback delegate. The WCF service is then called by the
service agent and the results are assigned to the People property.
So I understand that
(s,e) => this.People = e.Result
is a callback delegate and that the result of the function is placed into this.People. But I’m not understanding the “(s,e)” thing and generally am having a hard time grasping the syntax.
Would you mind explaining?
Effectively what is happening is:
1) The ViewModel is given an instance to IServiceAgent
2) The ViewModel is going to fetch and send data with the IServiceAgent. The viewmodel doesn’t know how to fetch the data, but tells the serviceagent to get it.
3) The IServiceAgent is not meant to be aware of the ViewModel or how to assign to it.
This is where your question kicks in. What is the delegate doing, and why does it need (s,e).
Why is this done?
The answer is because you want the IServiceAgent to update the viewModel, but to not have a reference to the ViewModel. How can that be done. Well it could be done using a normal method with a return type. But in this case the example article you have used wants to return its value asyncronously. This can be done by a tradtional method, but it would block your viewmodel. Effectivelly what you are implementing is an like event. The delegate is the contract for the event. So whoever implements the event has to conform to the contract that the delegate provides, for example:
-OR-
-OR-
Those all conform to the contract specified by the a click event (which is defined by the events delegate).
If you compare that to what is defined in the textbox class, it would look something like:
That therefore means that to implement the textbox click event you have to supply a method that has two inputs of Object sender, EventArgs a and has a void return type. This method can have any name.
The lambdas used in your question are delgates. Delegates are used to establish method contracts. Your lambda abides by the contract so it is valid. What (s,e) means is up to the delegate of the contract you are abiding by which is:
which I belive will generate something like:
This might seem a bit crazy to understand why its so hard to see what s and e are, but intellisense should (it works for me with resharper) show the types of s,e. The syntax of (s,e) is very common and the first one will almost always be the same as the .net events being (Object,EventArgs)