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 can overload your method. One method contains one parameter
GetFooBar(int a)
and the other contain both parameters,GetFooBar(int a, int b)
For just in case if someone wants to pass a callback (or
delegate
) as an optional parameter, can do it this way.Optional Callback parameter:
You can try this too
Type 1
public void YourMethod(int a=0, int b = 0) { //some code }
Type 2
public void YourMethod(int? a, int? b) { //some code }
The typical way this is handled in C# as stephen mentioned is to overload the method. By creating multiple versions of the method with different parameters you effectively create optional parameters. In the forms with fewer parameters you would typically call the form of the method with all of the parameters setting your default values in the call to that method.
In C#, I would normally use multiple forms of the method:
UPDATE: This mentioned above WAS the way that I did default values with C# 2.0. The projects I'm working on now are using C# 4.0 which now directly supports optional parameters. Here is an example I just used in my own code:
I had to do this in a VB.Net 2.0 Web Service. I ended up specifying the parameters as strings, then converting them to whatever I needed. An optional parameter was specified with an empty string. Not the cleanest solution, but it worked. Just be careful that you catch all the exceptions that can occur.