Reputation: 8937
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)
Upvotes: 4
Views: 500
Reputation: 116528
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:
Set a default of null and coalesce it as you use it:
public void MyMethod(string myParam1, string myParam2 = null)
{
Console.WriteLine(myParam2 ?? myParam1);
}
Use overloading:
public void MyMethod(string myParam1, string myParam2)
{
Console.WriteLine(myParam2);
}
public void MyMethod(string myParam1)
{
MyMethod(myParam1, myParam1);
}
Upvotes: 2
Reputation: 98858
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.
Upvotes: 2
Reputation: 5607
In order to perform what you want you'll need to use an overload instead of an optional parameter.
Upvotes: 3
Reputation: 149058
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.
Upvotes: 6