I’ve looked further down the documentation (this chapter in fact) and found some more, very interesting stuff on generics that make my solution with delegates a bit clumsy and non-elegant. When declare a generic class or method the type parameter can be limited to what types it can take using constraints. So in my solution the row:
public static TWebService CreateWebService(string WebServiceURL) where TWebService : SoapHttpClientProtocol
means that TWebService must be of SoapHttpClientProtocol type.
However I ran into a bit of confusion when I wanted to instantiate TWebService. The compiler was not happy when I wrote: // This won’t compile TWebService t = new TWebService();
That is until I discovered another constraint - the Constructor Constraint. By using this constraint you can constrain the types that is allowed to types with an empty (parameterless) constructor. And that will allow you to instantiate TWebService and the compiler will find the right constructor at runtime.
So here’s the syntax:
public static TWebService CreateWebService(string WebServiceURL) where TWebService : SoapHttpClientProtocol, new() { // This will be ok TWebService t = new TWebService(); }
Much nicer code without the previous delegate solution.