I would like to use the Null-Conditional Operator to check the SubscriptionExpires
property below.
public partial class Subscription
{
[Key]
public int SubscriptionId { get; set; }
public string SubscriberId { get; set; }
public DateTime? SubscriptionExpires { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }
}
A subscription is returned by
var subscription = _customersContext.Subscriptions.Where(s => s.SubscriptionId == user.SubscriptionId).FirstOrDefault();
However if Subscription
is null, Subscription?.SubscriptionExpires
returns a null reference exception
, so we are still left with the old
if (subscription != null)
How do I use the Null-Conditional Operator to read a property when the parent object can be null?
How do I use the Null-Conditional Operator to read a property when the parent object can be null?
You do it just as you did with Subscription?.SubscriptionExpires
. This will not throw a NullReferenceException
, but it will return DateTime?
. If you try to use a the DateTime?
's value then you'll get an exception. So this will not throw:
var expiration = Subscription?.SubscriptionExpires;
But this may:
DateTime? expiration = Subscription?.SubscriptionExpires;
DateTime expiration.Value;
If you want that "var expiration" should never throw exception while using it as DateTime datatype you can use
var expiration = subscription?.SubscriptionExpires ?? DateTime.MinValue;