Michael Conner
Michael Conner

Reputation: 19

Fails on encountering null

This code is part of a Shopify Sync utility. Never has failed, until we encountered a product with no value in the CompareTo Shopify field, not that we have a product with no CompareTo value.

private Decimal? GetComparePrice(long? productId, long? variantId, List<Product> products)
{
    var product = products.Where(x => x.Id == productId).FirstOrDefault();
    var variantData = product.Variants.Where(x => x.Id == variantId).FirstOrDefault();

    return variantData != null ? variantData.CompareAtPrice : null;
}

How do I get my function to return null if the CompareTo value is null?

Upvotes: 1

Views: 72

Answers (1)

Jesse Johnson
Jesse Johnson

Reputation: 1718

Try using the ?. null-conditional operators on properties that have potential of being null.

Here is a modified version of your method that returns null, instead of throwing an exception, when a product, variant or CompareAtPrice is null:

private decimal? GetComparePrice(long? productId, long? variantId, List<Product> products)
{
    var product = products.FirstOrDefault(p => p.Id == productId);
    var variant = product?.Variants?.FirstOrDefault(v => v.Id == variantId);
    return variant?.CompareAtPrice;
}

Here is a link to run this example via .NET Fiddle.

Upvotes: 3

Related Questions