Moons
Moons

Reputation: 3854

Function Overloading in WCF

I want to implement function overloading in WCF but i am not allowed to do so

    [OperationContract]
    [WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Json)]
    branch_view[] GetBranches();

    [OperationContract]
    [WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Json)]
    branch_view[] GetBranches(int pageNo , int pageSize);

The error i got is:

Cannot have two operations in the same contract with the same name, methods GetBranches and GetBranches in type QHRService.IEntityService violate this rule. You can change the name of one of the operations by changing the method name or by using the Name property of OperationContractAttribute.

Why WCF does not allow Function overloading.

I can change the name to get my function work but any reasons?

Any help is appreciated

Upvotes: 1

Views: 2885

Answers (3)

xtrem
xtrem

Reputation: 1779

WCF Doesn't allow overloading because most underlying communication protocols such as SOAP do not support overloading.

Overloading is a feature of C#, and WCF fills the gap by providing you with the Name property of the OperationContract attribute as @PraveenLearnsEveryday described.

If you are designing an interface (or class) who's only purpose is to be exposed as a WCF contract, then why go through the hassle. Just name your methods without overloading them.

On the other hand, if you are adapting an existing interface (or class) to WCF, you don't have to give-up that nice feature C# provides you. Overloading is a good and meaningful feature. Keep using it and use the OperationContract to rename the method. If you absolutely need to use that overloading feature on the client side, edit the auto generated proxy to match the server-side contract. This will work perfectly fine.

The only point I am making is that you do not have to give-up overloading to work with WCF.

Upvotes: 2

PraveenLearnsEveryday
PraveenLearnsEveryday

Reputation: 595

Conceptually WCF provides overloading using an attribute called Name for any OperationContract.

public interface IMyService
{
   [OperationContract(Name = "GetStringWithParam")]
   string GetString(DateTime date);

   [OperationContract(Name = "GetStringWithoutParam")]
   string GetString();
}

But i don't prefer it as it is sometimes lead to confusion.

Upvotes: 3

AakashM
AakashM

Reputation: 63378

WCF is designed to be a completely generic communications framework - which means that clients might not be .NET-based, and therefore might not have any understanding of method overloading.

There is functionality available for having methods with the same name, but it's a pain to get working reliably; I would strongly recommend just biting the bullet and having different method names, even though it feels 'wrong'.

Upvotes: 5

Related Questions