C
C#3y ago
Binto86

set default value of parameter to other parameter [Answered]

ok, i am aware that this is probably not possible, but can i set default value of parameter x to value of parameter y? consider this example:
public void MyMethod(string x, string y=x)
{
//some code
}
public void MyMethod(string x, string y=x)
{
//some code
}
would this be possible?
11 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
senox13
senox133y ago
There could absolutely be cases in which that makes sense. You can do that at the beginning of the method and use a sentinel value for the default argument value Or null, since it's a string
Binto86
Binto86OP3y ago
i started doing some library that generates some sql from json and i want the user to be able to say that column names are not the same as json fields, i know i can do it with overload, but i wanted to know if it is possible like this, mostly out of curiosity
senox13
senox133y ago
public void MyMethod(string x, string y=null)
{
if(y==null)
x=y;
//some code
}
public void MyMethod(string x, string y=null)
{
if(y==null)
x=y;
//some code
}
Binto86
Binto86OP3y ago
ok thats interesting approach, but at this point i think that it is easier to do it like this:
void MyMethod(string x, string y){
//my code here
}
void MyMethod(string x)=>MyMethod(x,x);
void MyMethod(string x, string y){
//my code here
}
void MyMethod(string x)=>MyMethod(x,x);
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
senox13
senox133y ago
Yep, both can be used exactly the same ways, though the first would be more DRY to document imo Irrelevant if you aren't adding XML docs
Binto86
Binto86OP3y ago
oh i am probably
senox13
senox133y ago
I'd definitely opt for my initial chunk of code there. It'll be half the typing to document
Binto86
Binto86OP3y ago
ok anyways, thanks for help, i am going to close this thread !close
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server