3

I know that in C# it is possible to define optional parameters. My question is directed at how flexible this is.

Let f be a function as below, with a mandatory and b, c optional :

class Test {
   public void f(int a, int b = 2, int c = 3) {
      //...
   }
}

Now, I know I can call the function in the following ways :

f(1) -> a equals 1, b equals 2, c equals 3

f(11,22) -> a equals 11, b equals 22, c equals 3

f(11,22,33) -> a equals 11, b equals 22, c equals 33

How do I do to not specify b, but a and c ?

2
  • I'm asking this because I need to wrap up some calls to Excel macros with .net 3.5. The annoying thing is that some of these macros have 30 or more params. In VBA, setting params selectively is easy, in C# I need to wrap those calls as I am forced to stuff unused values to Type.Missing Commented Feb 2, 2012 at 10:44
  • 1
    It is precisely because libraries like the Excel and Word interop libraries have those methods with 30+ params that we added optional parameters to C#. Note that we also added named arguments, and we added the ability to elide ref arguments on calls to legacy object models. (ref arguments may not be elided on regular C# library calls.) All three features are necessary to make calls to Excel and Word look nice. Commented Feb 2, 2012 at 16:49

5 Answers 5

7

Try:

f(11, c: 33)

And take a look at the documentation

Sign up to request clarification or add additional context in comments.

Comments

2

You can prefix the parameter with the argument name:

f(1, c:3);

Comments

2

Using named arguments:

f(a: 5, c: 6);

Although, strictly speaking in my example, you don't have to qualify the a:

f(5, c: 6);

Comments

0

You use named parameters:

f( a:100, c:300);

Comments

0

Another possibility would be to define the method with other parameters and call the original one with them using this syntax:

public void f(int a, int c = 3) => f(a, 2, c)

More comfortable usability if you call it, but gets fiddly to define if you have more than 2 optional parameters .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.