Reputation: 677
At first I tried to write an If-Then-Else statement
using a ternary operator
.
It works fine then Just out of curiosity I decided to write the same code using a
null-coalescing operator
but it doesn't work as expected.
public System.Web.Mvc.ActionResult MyAction(int? Id)
{
string MyContetnt = string.Empty;
//This line of code works perfectly
//MyContent = Id.HasValue ? Id.Value.ToString() : "Id has no value";
//This line of code dosent show "Id has no value" at all
MyContetnt = (System.Convert.ToString(Id) ?? "Id has no value").ToString();
return Content(MyContetnt);
}
If I run the program through the route Mysite/Home/MyAction/8777 everything is perfect and the entered Id
number will be shown.
But if I run the program without any Id
through the route MySite/Home/MyAction nothing will happen and MyContetnt
will be empty whereas I expect to see "Id has no value" on the screen.
Am I missing something?
Edit: I am curious that Is it possible to write the code by using ?? ( null coalescing operator )?
Upvotes: 2
Views: 1167
Reputation: 2585
Convert.ToString()
results in an Empty string when the conversion has failed. So the null coalescing operator won't detect a null but an Empty string
You should use:
MyContetnt = Id.HasValue ? System.Convert.ToString(Id.Value) : "Id has no value";
Upvotes: 6
Reputation: 113222
Convert.ToString()
, when acting on an int?
will produce either a numerical string (if the int?
has a value) or an empty string (otherwise).
Therefore, it's not producing null
, it's producing ""
, and "" ?? x == ""
.
Upvotes: 2