Why method overloading is not allowed in WCF?

C#.NetWcfOverloading

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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);
}

Solution 2 - C#

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.

Solution 3 - C#

The reason being that WCF is supposed to be universally usable by different clients and those clients do not have to be .NET and may also not allow Operator/Method overloading in their frameworks. If that is the case, then this method becomes unusable by those frameworks and therefore to ensure it is universally usable, WCF disallows and provides you with a name property in the OperationContract attribute to specify a different name. If the client is a .NET, then WCF will automatically show it as a method overload but otherwise it will generate a new method with the name specified in the name property.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSleiman JneidiView Question on Stackoverflow
Solution 1 - C#David Z.View Answer on Stackoverflow
Solution 2 - C#Wiktor ZychlaView Answer on Stackoverflow
Solution 3 - C#BaahubaliView Answer on Stackoverflow