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 tha
You can overload your method. One method contains one parameter GetFooBar(int a)
and the other contain both parameters, GetFooBar(int a, int b)
You can use optional parameters in C# 4.0 without any worries. If we have a method like:
int MyMetod(int param1, int param2, int param3=10, int param4=20){....}
when you call the method, you can skip parameters like this:
int variab = MyMethod(param3:50; param1:10);
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 :)
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:
public static bool IsOnlyOneElement(this IList lst, Action callbackOnTrue = (Action)((null)), Action callbackOnFalse = (Action)((null)))
{
var isOnlyOne = lst.Count == 1;
if (isOnlyOne && callbackOnTrue != null) callbackOnTrue();
if (!isOnlyOne && callbackOnFalse != null) callbackOnFalse();
return isOnlyOne;
}
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.
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.