Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you use optional parameters in C#?

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?

like image 675
Kalid Avatar asked Oct 14 '08 01:10

Kalid


People also ask

Can you have optional parameters in C?

C does not support optional parameters.

What is the use of optional parameter?

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.

How do you pass optional parameters?

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.

How do you define optional parameters?

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.


2 Answers

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.

like image 194
Alex from Jitbit Avatar answered Oct 03 '22 01:10

Alex from Jitbit


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); 
like image 45
Tim Jarvis Avatar answered Oct 03 '22 01:10

Tim Jarvis