Use Null Conditional Operator on property of Null Object

c# c#-6.0 entity-framework-core

Question

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?

Accepted Answer

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;

Popular Answer

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;


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why