How to do Method Overloading in WCF?
Method or Operation overloading is one of the most important feature of OOPS. In programming languages like C, C++ and C#, this feature is heavily used by developers. While writing Service definition you may come across when you need to overload operations.
Let us go ahead and write Service with overloaded function as following. In below ServiceContract I am creating two methods and overloading them with different parameters.
[ServiceContract] public interface IService1 { [OperationContract] int Add(int number1, int number2); [OperationContract] string Add(string text1, string text2); }
I implemented service as below,
public class Service1 : IService1 { public int Add(int number1, int number2) { return number1 + number2; } public string Add(string text1, string text2) { return text1 + text2; } }
I left default EndPoint configuration and hosting. When I ran service I encountered following exception,
So clearly by default WCF does not allow you to overload methods in service. However there is one attribute in OperationContract which can allow you to overload method at service end. You need to set Name parameter of OperationContract to manually enable overloading at service side.
To achieve overloading at Service side I set Name parameter of both function as follows,
[ServiceContract] public interface IService1 { [OperationContract(Name="AddNumber")] int Add(int number1, int number2); [OperationContract(Name="AddString")] string Add(string text1, string text2); }
Even though we have achieved overloading at Service side at client side method exposed with different name as set in Name parameter. At client side you will get method exposed as following,
So on asking you can say that by setting Name parameter value of OperationContract we can achieve Operation or Method overloading in WCF. I hope you find this post useful. Thanks for reading.
Leave a Reply