Sunday, March 08, 2009

Service Reference for method returning void and out parameter

The title is quite lengthy but I couldn't find a better one. In essence I'd like to make describe a little catch you might experience when generating a service reference within Visual Studio 2008 (it might apply to other versions as well). Suppose you have a service implemented in WCF (Windows Communication Foundation). The services exposes an operation as follows: void UpdateItem(ItemData data, out ServiceFault fault); (Yes, I know that faults should be handled differently but if you want to support Silverlight there are not too many alternatives at present since we are running inside a browser. I wrote about this before so won't go into details here.) Note that the class ServiceFault is a very simple class. The details are not relevant here. The point I want to make here is this. When you create a service reference to the service that provides the above the operation Visual Studio will generate the signature in the service client as follows: public ServiceFault UpdateItem(ItemData data); You will notice that the return value has change from void to ServiceFault, and that the new operation takes only one parameter and has no out parameter. While generally it is probably a smart assumption that for a void operation the first (or only) out parameter is turned into the return value you may not want this in all cases. For some users this behavior might even be surprising. It might make sense to argue that this is a violation of the principle of least surprise. In my particular case I wanted the signature to be consistent with other signatures from other operations in the same service. So I changed the service interface to: long UpdateItem(ItemData data, out ServiceFault fault); The implementation always returns 0 as a result. And now, when I update the service reference I get the expected matching signature generated, and all signatures for the operations within my service are now consistent. On second thought, though, I might actually try a different approach. What if the return value becomes of type ServiceResult? And if I actually have to return some values these can always become an out paramter. I'll give that thought a try and keep you posted.

0 comments:

Post a Comment

All comments, questions and other feedback is much appreciated. Thank you!