HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How can you use optional parameters in C#?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youhowuseoptionalcanparameters

Problem

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?

Solution

With C# 4.0 you can use optional parameters that work like this:

public void SomeMethod(int a, int b = 0)
{
   //some code
}

Code Snippets

public void SomeMethod(int a, int b = 0)
{
   //some code
}

Context

Stack Overflow Q#199761, score: 1284

Revisions (0)

No revisions yet.