Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).
We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b)
and the API has a method GetFooBar
taking query params like &a=foo &b=bar
.
The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?
You could use method overloading...
It depends on the method signatures, the example I gave is missing the "int b" only method because it would have the same signature as the "int a" method.
You could use Nullable types...
You could then check, using a.HasValue, to see if a parameter has been set.
Another option would be to use a 'params' parameter.
If you wanted to go with named parameters would would need to create a type to handle them, although I think there is already something like this for web apps.
I agree with stephenbayer. But since it is a webservice, it is easier for end-user to use just one form of the webmethod, than using multiple versions of the same method. I think in this situation Nullable Types are perfect for optional parameters.
optional parameters are nothing but default parameters! i suggest you give both of them default parameters. GetFooBar(int a=0, int b=0) if you don't have any overloaded method, will result in a=0, b=0 if you don't pass any values,if you pass 1 value, will result in, passed value for a, 0 and if you pass 2 values 1st will be assigned to a and second to b.
hope that answers your question.
Hello Optional World
If you want the runtime to supply a default parameter value, you have to use reflection to make the call. Not as nice as the other suggestions for this question, but compatible with VB.NET.
Surprised no one mentioned C# 4.0 optional parameters that work like this:
Edit: I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.
I have a web service to write that takes 7 parameters. Each is an optional query attribute to a sql statement wrapped by this web service. So two workarounds to non-optional params come to mind... both pretty poor:
method1(param1, param2, param 3, param 4, param 5, param 6, param7) method1(param1, param2, param3, param 4, param5, param 6) method 1(param1, param2, param3, param4, param5, param7)... start to see the picture. This way lies madness. Way too many combinations.
Now for a simpler way that looks awkward but should work: method1(param1, bool useParam1, param2, bool useParam2, etc...)
That's one method call, values for all parameters are required, and it will handle each case inside it. It's also clear how to use it from the interface.
It's a hack, but it will work.