sheepiiHD
sheepiiHD

Reputation: 326

Can you have optional parameters with a limiting condition?

I want to create a function with two optional parameters, but you can only choose one of the two optional parameters.

For example:

 public void DoThing (int foo = 0, string bar = "test") {
    if (foo != 0)      // Do something with foo
    if (bar != "test") // Do something with bar
 }

However, if someone does DoThing(1, "Hello World!");, it will call both statuses and I don't want to allow them to use both.

Is it possible force them to fix this mistake before compiling the code?

Upvotes: 0

Views: 50

Answers (2)

Rahul
Rahul

Reputation: 77936

probably create two overload of the method like

 public void DoThing (string bar, int foo = 0){
// code here
 }

 public void DoThing (int foo , string bar = "test"){
// code here
 }

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Why not overload ?

public void DoThing (int foo) {
  // Do something with foo
}

public void DoThing (string bar) {
  // Do something with bar
}

public void DoThing (int foo, string bar) {
  // Do something with foo and bar
}

Upvotes: 2

Related Questions