-3

can any body help me with this code. I have written this code in asp.net MVC c# but I don't know why I used ? in the if statement logic. I want to know what mean booking?.UserID ??

public async Task<IActionResult> Details(int id)
{
    //get the user who already logged in
    IdentityUser user = await 
    _userManagerService.FindByNameAsync(User.Identity.Name);

    //get single package 
    Booking booking = _bookingDataService.GetSingle(b => b.BookingID 
               == id);

    if ((booking?.UserID ?? "A") == (user?.Id ?? "B"))
    {
        //create vm
        BookingDetailsViewModel vm = new BookingDetailsViewModel
        {
            BookingDate=booking.BookingDate,
            Price=booking.Price,
            Qty=booking.Qty
        };
        //pass to view
        return View(vm);
        }
        else
        {
            return RedirectToAction("Index", "Customer");
        }
    }
}
AakashM
  • 62,551
  • 17
  • 151
  • 186
  • 4
    Possible duplicate of [What does question mark and dot operator ?. mean in C# 6.0?](https://stackoverflow.com/questions/28352072/what-does-question-mark-and-dot-operator-mean-in-c-sharp-6-0) – CodeCaster Jun 20 '18 at 09:08
  • [?.](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators) - [??](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator) – Mike Jun 20 '18 at 09:12
  • You clearly didn't write it if you don't know what it means... – John M Jun 20 '18 at 09:23
  • Yes,bro .I used code that to avoid my problem in action method .when run app its work ,but if type on URL ex:Localhost:5000/Booking/Details/5 if id 5 not for how is login get exception . that's why i using and i need understand what exactly this mean. i don't under stand why this format write like this – islam kabaha Jun 20 '18 at 12:37

1 Answers1

1

MyVar?.SomeProperty checks if MyVar is null.

Writting var foo = MyVar?.SomeProperty is like writting var foo = ((MyVar == null) ? (null) : (MyVar.SomeProperty))

MyVar.SomeProperty ?? "SomeValue" checks if SomeProperty is null then it assign the value "SomeValue"

Writting var foo = MyVar.SomeProperty ?? "SomeValue" is like writting var foo = ((MyVar.SomeProperty == null) ? ("SomeValue") : (MyVar.SomeProperty))

Cid
  • 14,968
  • 4
  • 30
  • 45