Assume that this is a ServiceContract
[ServiceContract] public interface MyService { [OperationContract] int Sum(int x, int y); [OperationContract] int Sum(double x, double y); }
Method overloading is allowed in C#, but WCF does not allow you to overload operation contracts
The hosting program will throw an InvalidOperationException
while hosting
Method Over Loading in WCF. Since Overloading is possible with C# code and so we may assume that it might be possible too in WCF as we are using C# code for service methods. But, the answer is no if you implement the overloading as shown in the previous example.
You can change the name of an operation by changing the method name or using the name property of OperationContractAttribute. By default WSDL does not support operational overloading, but we can do this using the Name property of OperationContract. Now update your service reference and run the application.
Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call. ... It is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method.
This is a very common interview question as well: Is it possible to overload a web method in a web service? The answer is yes, you need to use MessageName property for this.
In a nutshell, the reason you cannot overload methods has to do with the fact that WSDL does not support the same overloading concepts present inside of C#. The following post provides details on why this is not possible.
http://jeffbarnes.net/blog/post/2006/09/21/Overloading-Methods-in-WCF.aspx
To work around the issue, you can explicitly specify the Name
property of the OperationContract
.
[ServiceContract] public interface MyService { [OperationContract(Name="SumUsingInt")] int Sum(int x, int y); [OperationContract(Name="SumUsingDouble")] int Sum(double x, double y); }
Because when invoking over HTTP/SOAP, having the same method name in your contract would mean that there's no way to determine which particular method the client is about to invoke.
Remember that when invoking web methods over http, arguments are optional and are initialized with default values if missing. This means that invocation of both methods could look exactly the same way over HTTP/SOAP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With