0

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?

0

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

Comments

3

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;

2 Comments

Thank you @Banketeshvar Narayan but why would that be necessary? Doesn't var take whatever type is returned ... and if that is null, isn't that ok?
@LongwordsBotherme, The Null Conditional Operator (?.) is used to handle Null reference exception and return just NULL instead of throwing exception. so if you assign that null value to "var expiration" then it may throw exception while you are assigning "expiration" any other DateTime variable or you have to use DateTime? The answer given by i3arnon is 100% correct but I have just given alternative that if you do not want to use Nullable data types (i.e. Using DateTime instead of DateTime?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.