Method Overloading in WCF: WCF Interview Series #1

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,

image

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.

image

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,

image

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.

6 thoughts on “Method Overloading in WCF: WCF Interview Series #1

  1. Pingback: Method Overloading in WCF: WCF Interview Series #1 | Sriramjithendra Nidumolu

  2. Pingback: Friday Five - May 17, 2013 - The Microsoft MVP Award Program Blog - Site Home - MSDN Blogs

  3. Pingback: Blog Posts of the Week (12th - 18th May 2013) - The South Asia MVP Blog - Site Home - TechNet Blogs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s