Default Values ​​for Additional Method Attributes

I have a method:

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

Is there a way to do this something like:

 public void MyMethod(string myParam1,string myParam2 = (myParam2 == "")?myParam1:myParam2) 
+4
source share
4 answers

No.

The default parameter values ​​must be known at compile time. The first passage you provided is the right way to do this. Or, as pointed out by other answers, specify an overload method that takes only one parameter.

+6
source

To accomplish what you need, you need to use overload instead of an optional parameter.

+3
source

There is no chance, I believe that you tried.

If you want to make such a process, the best parameters look like method overloading .

Overload resolution is a compilation mechanism for selecting the best member of a function to call a given list of arguments and to set candidate functions.

+2
source

Directly, since the default value must be known at compile time. The first method you describe is the right way to do this.

However, you could do:

  • Set the default value to null and combine it as you use it:

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

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

All Articles