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?
C does not support optional parameters.
What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported.
Surprised no one mentioned C# 4.0 optional parameters that work like this:
public void SomeMethod(int a, int b = 0) { //some code }
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.
Another option is to use the params keyword
public void DoSomething(params object[] theObjects) { foreach(object o in theObjects) { // Something with the Objects… } }
Called like...
DoSomething(this, that, theOther);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With