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?
An elegant and easy way which allows you to omit any parameters in any position, by taking advantage of nullable types is as follows:
Strings are already nullable types so they don't need the ?.
Once you have this method, the following calls are all valid:
When you define a method that way you have the freedom to set just the parameters you want by naming them. See the following link for more information on named and optional parameters:
Named and Optional Arguments (C# Programming Guide) @ MSDN