0

I have created a simplified scenario below of my problem. I need to set EmptyBookingAllowed to true or false, however AllowEmptyBooking will not exist in the config for certain customers.

How do I set EmptyBookingAllowed to true if the config.AllowEmptyBooking otherwise set it to the value of config.AllowEmptyBooking.

public Class BookingSession()
{
    public string Username {get; set;}
    public bool EmptyBookingAllowed {get; set;}
}

BookingSession session = new BookingSession(){ 
    Username            = "whatever",  
    EmptyBookingAllowed = config.AllowEmptyBookings
};
joehelsing
  • 83
  • 7

1 Answers1

0

Use the Null-coalescing operator:

EmptyBookingAllowed = (config?.AllowEmptyBookings ?? true);
Troy Turley
  • 659
  • 10
  • 28
  • it's not work for empty config. Better use `(config?.AllowEmptyBookings ?? true)` – Lofem Mar 02 '22 at 10:59
  • It should be `config?.AllowEmptyBookings ?? true` (`?.` instead of `?`): note, that if `AllowEmptyBookings` is `bool` it always exists, while `config` can be `null` – Dmitry Bychenko Mar 02 '22 at 11:00
  • Just to clarify, config will always exists, however config.AllowEmptyBookings may not always exist. – joehelsing Mar 02 '22 at 11:02
  • @joehelsing Then you need to use `bool?` instead of `bool` for the `AllowEmptyBookings` in your config class. – Dusan Mar 02 '22 at 11:06
  • @joehelsing if it is a `bool` and not a `bool?` (nullable), then it _always_ exists. – Franz Gleichmann Mar 02 '22 at 11:06
  • But I think it is better to intercept non-existent config case in the code that actually loads the config... In there, if config does not exists, you can populate it with the defaults (instead of making fields nullable)... That will make your code that actually uses config simpler. – Dusan Mar 02 '22 at 11:10