4

I have a method:

public void MyMethod(string myParam1,string myParam2="") { myParam2 = (myParam2 == "")?myParam1:myParam2; } 

Is there any way to do this something like:

public void MyMethod(string myParam1,string myParam2 = (myParam2 == "")?myParam1:myParam2) 

4 Answers 4

6

No.

The default value of parameters needs to be known at compile time. The first snippet you provided is the correct way to do this. Or as has been pointed out by other answers, provide an overload method that only accepts a single parameter.

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

Comments

3

In order to perform what you want you'll need to use an overload instead of an optional parameter.

Comments

2

There is no chance I believe what you tried to.

If you want to do process like this, best options looks like method overloading.

Overload resolution is a compile-time mechanism for selecting the best function member to invoke given an argument list and a set of candidate function members.

Comments

2

Not directly, as the default value must be known at compile time. The first method you describe is the correct way to do this.

However, you could do:

  1. Set a default of null and coalesce it as you use it:

    public void MyMethod(string myParam1, string myParam2 = null) { Console.WriteLine(myParam2 ?? myParam1); } 
  2. Use overloading:

    public void MyMethod(string myParam1, string myParam2) { Console.WriteLine(myParam2); } public void MyMethod(string myParam1) { MyMethod(myParam1, myParam1); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.