Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable type and .HasValue still throws a Null Exception

Tags:

c#

linq

I have a class describing the various Phones stored. Sometimes the Importance property can be null. Here is the class

public class PhoneTypeListInfo
{
    public string AccountNum { get; set; }
    public int PhoneType { get; set; }
    public string PhoneNum { get; set; }

    public int Importance { get; set; }
}

I have defined a function that will return a PhoneTypeListInfo if the Phone number and account number match a given set of values.

    protected PhoneTypeListInfo RetrievePhoneType(string info, string acctNumber)
    {
        PhoneTypeListInfo type = xPhoneTypeList.Where(p => p.PhoneNum == info && p.AccountNum == acctNumber).FirstOrDefault();

        return type;
    }

This all works great. The problem I'm having is with the linq query below.

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                  where x.Media == "Phone"
                  let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                  let xyz = x.Importance = (p.Importance as int?).HasValue ? p.Importance : 0
                  orderby p.Importance descending
                  select x).ToList();

What I am doing above is attempting to use a different class that has a different composition, except for obtaining the 'Importance' property from the PhoneTypeListInfo.

My question ultimately is, What do I need to do to allow p.Importance to be null, and set it to 0 if it is null, making x.Importance 0 as well.

like image 552
Chris Clark Avatar asked Nov 04 '25 21:11

Chris Clark


1 Answers

It is not that p.Importannce that is null, but p itself. That is the thing you need to check for null first. If you are using C# 6 you can use the ?. operator. You can also smiplifiy the logic of (p.Importance as int?).HasValue ? p.Importance : 0 to p.Importance ?? 0. Combining both you get

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                         where x.Media == "Phone"
                         let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                         let xyz = x.Importance = p?.Importance ?? 0
                         orderby p?.Importance descending
                         select x).ToList();
like image 80
Scott Chamberlain Avatar answered Nov 06 '25 21:11

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!