Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip optional parameters in C#?

Example:

public int foo(int x, int optionalY = 1, int optionalZ = 2) { ... } 

I'd like to call it like this:

int returnVal = foo(5,,8);  

In other words, I want to provide x and z, but I want to use the default for Y, optionalY = 1.

Visual Studio does not like the ,,

Please help.

like image 979
Ian Davis Avatar asked Jan 07 '11 21:01

Ian Davis


People also ask

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.

Can you have optional parameter in C?

C does not support optional parameters.

Are optional parameters bad practice?

The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.

How do you pass an optional parameter in C++?

You don't pass option parameters. You pass optional arguments! For more explicit control than that provided by reserving sentinel values, check out boost::optional<>.


1 Answers

If this is C# 4.0, you can use named arguments feature:

foo(x: 5, optionalZ: 8);  

See this blog for more information.

like image 188
Josiah Ruddell Avatar answered Sep 22 '22 23:09

Josiah Ruddell