简体   繁体   中英

Why doesn't the null coalescing operator work on my nullable int when I convert it to a string?

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 )?

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";

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 == "" "" ?? x == "" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM