tags:

views:

110

answers:

2

When you call a delegate object’s BeginInvoke, the system creates an object of type AsyncResult, but BeginInvoke returns a reference of type IAsyncResult interface ( which points to AsyncResult instance) . Why doesn’t BeginInvoke instead return a reference of type AsyncResult?

thanx

+6  A: 

This is standard interface based programming.

By returning an IAsyncResult, the framework is free to change the internal implementation at a later time, without breaking code written against the framework's API. This, in essence, telling us, as developers, that we should not care what type of implementation is used, provided the interface (IAsyncResult) is met.

If, instead, the actual AsyncResult class was returned, then changing to a different class would break existing code.

Also, this allows the framework to use the same interface (IAsyncResult) in multiple places, whether or not the AsyncResult class is appropriate. I've taken advantage of this, personally, as I've made my own asynchronous functions which return IAsyncResult backed by a different class, which stored the information which was important to me. This allows my own code to work like the framework, without restricting me to the framework's implementation.

Reed Copsey
Makes sense. Thanx for your help
AspOnMyNet
Heaven help us if they need to add another function to that interface, however.
Will
+1  A: 

Because it doesn't always return an AsyncResult. The delegate target may exist in another execution context, a RealProxy derived class may implement a proxy for it. Remoting would be an example. Returning an interface type makes that transparent.

Hans Passant