WCF Snippet Tutorial - Overloading Methods

Skill

WCF Snippet Tutorial - Overloading Methods

Posted in:

This snippet will show you how to add overloaded functions to your WCF service contracts.

In our introductory WCF tutorial, I created a basic service contract that accepted a string and returned a reversed version of it. For this tutorial, I want to overload this function to also accept a character array. If I were to attempt to just stick in my overload like this:

[ServiceContract]
public interface IStringReverser
{
  [OperationContract]
  string ReverseString(string value);

  [OperationContract]
  string ReverseString(char[] value);
}

It would result in this exception being thrown at runtime:

Cannot have two operations in the same contract with the same name, methods ReverseString and ReverseString in type WCFServer.IStringReverser 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.

By default, every operation contract gets a name that is set to the name of method. In WCF, you cannot have two operation contracts with the same name. Fortunately, this is very easy to fix by simply setting the name property of the operation contract attribute.

[ServiceContract]
public interface IStringReverser
{
  [OperationContract(Name = "ReverseStringFromString")]
  string ReverseString(string value);

  [OperationContract(Name = "ReverseStringFromCharArray")]
  string ReverseString(char[] value);
}

And there you have it. We now have a WCF service contract with overloaded methods.

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.