58

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.

Himanshu
  • 31,810
  • 31
  • 111
  • 133
Ian Davis
  • 19,091
  • 30
  • 85
  • 133

3 Answers3

88

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

foo(x: 5, optionalZ: 8); 

See this blog for more information.

dakab
  • 5,379
  • 9
  • 43
  • 67
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • 4
    For the record, I think it's more accurate to call them named *arguments*. Parameters have *always* had names! – Jon Skeet Jan 07 '11 at 21:30
  • @Jon I agree that it would make more sense, but why then does everyone (including both the links @Josiah and I provide) used the term named parameters? Using Google as a comparison, "named parameters" returns double the results "named arguments" does (using quotes). – moinudin Jan 07 '11 at 21:33
  • 2
    @marcog - http://stackoverflow.com/questions/306085/shouldnt-c-4-0s-new-named-parameters-feature-be-called-named-arguments – Josiah Ruddell Jan 07 '11 at 21:37
  • @marcog: Not everyone does :) Many people do because some influential writers no doubt did early on. That doesn't mean it's correct to follow their lead. In particular though, the *spec* uses the term "named argument" - see section 7.5.1. – Jon Skeet Jan 07 '11 at 21:38
  • 2
    Do not confuse the C# 4 language and the C# 4 compiler. You can target .net 3.5 and still use optional parameter, as long as you compile with the c#4 compiler – Pierre-Alain Vigeant Jan 07 '11 at 21:43
  • @Josiah BTW, `optionalX` should be `optionalY` to correctly answer the question. – moinudin Jan 07 '11 at 21:44
  • @marcog - actually it would be optionalZ if i was reading intentions. – Josiah Ruddell Jan 07 '11 at 21:46
20

In C# 4.0 you can name the arguments occurring after skipped defaults like this:

int returnVal = foo(5, optionalZ: 8);

This is called as named arguments. Several others languages provide this feature, and it's common form them to use the syntax foo(5, optionalZ=8) instead, which is useful to know when reading code in other languages.

moinudin
  • 134,091
  • 45
  • 190
  • 216
0

Another dynamic way to supply parameters of your choise is to implement your method(s) in a class and supply named parameters to the class constructor. Why not even add calls to methods on same line of code as mentioned here : How to define named Parameters C#

var p = new PersonInfo { Name = "Peter", Age = 15 }.BuildPerson();

Community
  • 1
  • 1
tofo
  • 388
  • 3
  • 8