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?

23 s
23

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.

Leave a Comment