Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the null coalescing operator breaking my string assignment in c#?

Tags:

c#

asp.net

I'm creating a query string in a web form, and I'm dealing with values from the parameters that might be null. There are lots of ways to check and fix these, but the most elegant one I found is the following:

string pass;
pass = "BillabilityDetail.aspx?_startDate=" + _startDate.Text + "&_endDate=" + _endDate.Text + 
       "&_isContractor=" + _isContractor.SelectedValue + "&_busUnit=" + _busUnit.Text 
       + "&_projectUnit=" + _projectUnit.SelectedValue + "&_leadCon=" + _leadCon.Value ?? -1
       + "&_acctExec=" + _acctExec.Value ?? -1 + "&_isBillable=" + _isBillable.SelectedValue + 
       "&_isActive=" + _isActive.SelectedValue + "&_include=" + _include.SelectedValue;

The only issue is... it doesn't work. When the code reaches this part,

"&_leadCon=" + _leadCon.Value ?? -1 + "&_acctExec=" + _acctExec.Value ?? -1 

the string stops assigning values. So the string would end with &_leadCon=. I know of ways to work around this, but I don't know why it stopped working in the first place. Any tips?

like image 212
proseidon Avatar asked Jul 09 '12 15:07

proseidon


2 Answers

The + has higher precedence than ??, thus you need to surround your null-coalescing expressions in parenthesis.

"&_leadCon=" + (_leadCon.Value ?? -1) + "&_acctExec=" + (_acctExec.Value ?? -1 )

See the precedence chart here

like image 146
James Michael Hare Avatar answered Oct 06 '22 00:10

James Michael Hare


Try using parentheses to tell the compiler exactly what you mean.

For example:

"&_leadCon=" + (_leadCon.Value ?? -1) + "&_acctExec=" + (_acctExec.Value ?? -1)
like image 36
tomfanning Avatar answered Oct 06 '22 00:10

tomfanning