Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values for method optional attributes

Tags:

c#

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)
like image 480
Alex Avatar asked Dec 12 '22 17:12

Alex


2 Answers

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.

like image 139
p.s.w.g Avatar answered Dec 30 '22 23:12

p.s.w.g


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

like image 41
JG in SD Avatar answered Dec 31 '22 01:12

JG in SD