How to create overload methods in WCF service with C#

Before some days I have posted an blog about How to create overloaded web methods in asp.net web service? In this post I am going to explain how we can create overload methods in WCF(Windows Communication Foundation) service with C# language.

So let’s consider same Hello world example which we have used web service overload method. Let’s create two methods HelloWorld one is with name and another is without parameter. For WCF service we have to first create interface following is a code for that.

using System.ServiceModel;

namespace WebApplication4
{
    [ServiceContract]
    public interface IHelloWorldOverload
    {
        [OperationContract]
        string HelloWorld();

        [OperationContract]
        string HelloWorld(string name);

    }
}

Now our interface is ready so it’s time to implement this interface and create WCF service like following.

namespace WebApplication4
{
    public class HelloWorldOverload : IHelloWorldOverload
    {
        public string HelloWorld() {
            return "Hello World";
        }

        public string HelloWorld(string name) {
            return string.Format("Hello World {0}", name);
        }
    }
}

So now we are done with WCF service and let’s do compilation so if you compile this It will compile as this is a valid code. Let’s run it in browser. Now the problem will start. You will get following error.

“Cannot have two operations in the same contract with the same name, methods HelloWorld and HelloWorld in type WebApplication4.IHelloWorldOverload 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.”

Overload Methods in WCF Service

Read more

Published Saturday, February 02, 2013 4:54 PM by Jalpesh P. Vadgama
Filed under: , , ,

Comments

No Comments