Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use optional parameters when implementing an interface for a WCF

In my interface I have declared this.

[OperationContract]
[WebGet]
String GetStuff(String beep, String boop = "too lazy to type");

I implemented it as follows.

String GetStuff(String beep, String boop = "too lazy to type") { ... }

It compiles and uploads as my WCF service. However, when I used it as a web reference and try to execute the code below, I get the compiler whining and weeping about no method with signature of a single parameter. The last line is the problem.

How can I then be too lazy to type by default?

ServiceClient client = new ServiceClient();
client.GetStuff("blobb", "not lazy");
client.GetStuff("blobb");
like image 389
Konrad Viltersten Avatar asked Jun 11 '13 11:06

Konrad Viltersten


People also ask

How would you implement optional parameters?

You can use optional parameters in Methods, Constructors, Indexers, and Delegates. Each and every optional parameter contains a default value which is the part of its definition. If we do not pass any parameter to the optional arguments, then it takes its default value.

How do you pass optional parameters in C#?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

What is the use of optional parameter?

By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.

Can you make a parameter optional?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.


2 Answers

Simply: default arguments are not supported.

By design and with reason. We use C# to write WCF contracts but that's a notational trick. Not every C# language feature can be implemented in SOAP, REST or JSon.

like image 185
Henk Holterman Avatar answered Oct 25 '22 16:10

Henk Holterman


You can try this, overloading the function.

[OperationContract]
MyResponse GetData(); 

[OperationContract(Name = "GetDataByFilter")]
MyResponse GetData(string filter);

Then another option is to use a DataContract instead of multiple parameters, and set IsRequired to false on the appropriate DataMembers, like explained in this question.

like image 26
Mez Avatar answered Oct 25 '22 15:10

Mez