Search code examples
c#exceptionsqlparameter

Exception thrown when it shouldn't be


    private async Task<long> InsertCustomerRecord(CreateCustomerModel model)
    {

        Int64 phoneNumber = 0;
        var isParsed = Int64.TryParse(model.PhoneNumber, out phoneNumber);
        if (!isParsed)
            phoneNumber = 0;
        var USPSAddressValidatedId = (int)model.USPSAddressValidated;
        try
        {
            IDataParameter[] parameters = new IDataParameter[]
            {
            new SqlParameter("@FirstName", model.FirstName.ToUpper()),
            new SqlParameter("@LastName", model.LastName.ToUpper()),
            //new SqlParameter("@MiddleInitial", model.MiddleInitial),
            new SqlParameter("@AddressLine1",model.AddressLine1.ToUpper() ?? ""),
            new SqlParameter("@AddressLine2",model.AddressLine2.ToUpper() ?? ""),
            new SqlParameter("@City",model.City.ToUpper()),
            new SqlParameter("@State",model.State.ToUpper()),
            new SqlParameter("@CountyCode",model.CountyCode.ToUpper()),
            new SqlParameter("@ZipCode",model.ZipCode),
            new SqlParameter("@DateOfBirth",model.DateOfBirth.ToShortDateString()),
            new SqlParameter("@Phone",phoneNumber),
            new SqlParameter("@Email",model.EmailAddress.ToUpper()??""),
            new SqlParameter("@PersonalRepresentative",model.CustomerClass.ToUpper()),
            new SqlParameter("@ExpiryDate", model.ExpirationDate),
            new SqlParameter("@CustomerClass", model.Customer_Class),
            new SqlParameter("@USPSAddressValidated",USPSAddressValidatedId ),
            new SqlParameter("@ImportFromLegacySystem", model.ImportFromLegacySystem)
            };
        
            return await InsertUpdateProcedure("RF_InsertCustomerCard", parameters);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return 0;
        }
    }

The exception thrown is

{"Object reference not set to an instance of an object."}
    Data: {System.Collections.ListDictionaryInternal}

Solution

  • If you have something that you suspect might be null:

    model.EmailAddress
          ^^^^^^^^^^^^
       this might be null
    

    You need to use the null propagating operator on it:

    model.EmailAddress?.ToUpper() ?? ""
                      ^^
    

    This means if it is null, then evaluation of the chain of operations will cease at the point that .EmailAddress returns null, and the sub-expression (model.EmailAddress?.ToUpper()) will resolve to null. It will then be picked up by the null coalescing operator ?? and turned into whatever you've put on the right hand side of the operator. If it's a constant, like "" then the whole expression is guaranteed to not be null

    You can use these operators multiple times, on property and method return values:

    thing.Prop?.Method() ?? thing.OtherProp?.OtherMethod()?.AnotherProp ?? "Constant"
    

    There is also a null tolerant indexer if collections might be null:

    //in case the collection is null, or the thing at index 0 is null, or its Property is null...
    thing.Collection?[0]?.Property?.Something() ...
                    ^^