Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why method overloading is not allowed in WCF?

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

like image 486
Sleiman Jneidi Avatar asked Apr 23 '12 07:04

Sleiman Jneidi


People also ask

Can we do method overloading in WCF service?

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.

How is method overloading implemented in WCF?

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.

Why method overloading is not possible with?

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.

Is overloading possible in Web services?

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.


2 Answers

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); } 
like image 129
David Z. Avatar answered Sep 20 '22 08:09

David Z.


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.

like image 43
Wiktor Zychla Avatar answered Sep 24 '22 08:09

Wiktor Zychla