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?
A little late to the party, but I was looking for the answer to this question and ultimately figured out yet another way to do this. Declare the data types for the optional args of your web method to be type XmlNode. If the optional arg is omitted this will be set to null, and if it's present you can get is string value by calling arg.Value, i.e.,
What's also decent about this approach is the .NET generated home page for the ws still shows the argument list (though you do lose the handy text entry boxes for testing).
Instead of default parameters, why not just construct a dictionary class from the querystring passed .. an implementation that is almost identical to the way asp.net forms work with querystrings.
i.e. Request.QueryString["a"]
This will decouple the leaf class from the factory / boilerplate code.
You also might want to check out Web Services with ASP.NET. Web services are a web api generated automatically via attributes on C# classes.
From this site:
http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1
C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:
In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.
optional parameters are for methods. if you need optional arguments for a class and you are:
using c# 4.0: use optional arguments in the constructor of the class, a solution i prefer, since it's closer to what is done with methods, so easier to remember. here's an example:
using c# versions previous to c#4.0: you should use constructor chaining (using the :this keyword), where simpler constructors lead to a "master constructor". example:
Another option is to use the params keyword
Called like...
You can use optional parameters in C# 4.0 without any worries. If we have a method like:
when you call the method, you can skip parameters like this:
C# 4.0 implements a feature called "named parameters", you can actually pass parameters by their names, and of course you can pass parameters in whatever order you want :)