Search code examples
c#asp.net-mvcnullablenull-coalescing

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


Solution

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