-1
    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}
software is fun
  • 7,286
  • 18
  • 71
  • 129
  • 2
    On which line? Code like this is suspicious: `model.EmailAddress.ToUpper()??""` - if EmailAddress is a string, it might be null, but `ToUpper()` will not return null if called on a non-null instance so you wouldn't coalesce it.. If you know EmailAddress could be null then calling `.ToUpper()` on it would result in a crash; the code should look like `model.EmailAddress?.ToUpper()??""` - the `?.` will not call `ToUpper` on a null emailaddress - it will just short cut straight to null, and then `??` *would* make sense – Caius Jard Dec 01 '21 at 15:53
  • 1
    ListDictionaryInternal isn't even in the code snippet so we can't really tell what's wrong. – Joseph Thompson Dec 01 '21 at 15:53
  • Can you include more information/scope on this issue? – Aaron P. Dec 01 '21 at 15:54
  • @AAP the entire method is posted. – software is fun Dec 01 '21 at 15:56
  • `.ToUpper()` cannot return `null`, so obviously `x.ToUpper() ?? ""` is wrong. – Camilo Terevinto Dec 01 '21 at 15:57
  • Exceptions come with line numbers and a stack. You have a lot of code there, showing that information would help a lot. The way to figure this out is break just before this code is executed and check which data is null – Flydog57 Dec 01 '21 at 15:58
  • 1
    You probably want use **null propagation** `?` in combination with **null-coalescing** `??` e.g. `model.SomeProperty?.ToUpper() ?? ""`. *UPD*: late seen my comment duplicates @Caius Jard comment. – Auditive Dec 01 '21 at 15:58
  • 1
    "Exception is thrown when it _should_ be" FTFY – The2Step Dec 01 '21 at 16:00
  • THanks everyone!. I can't believe I was that dumb! I missed it. Please put it as the answer so I can give you credit and it may help others @CaiusJard – software is fun Dec 01 '21 at 16:07
  • Review note: The first 4 lines of this method can be reduced to 1 line: `Int64.TryParse(model.PhoneNumber, out Int64 phoneNumber);` – madreflection Dec 01 '21 at 16:11
  • Another review note: calling `new SqlParameter(paramName, value)` is (depending on what you do with `parameters `, I suspect assign it to a SqlParameterCollection) highly likely to be the effective equivalent of calling `command.Parameters.AddWithValue`, and [use of AddWithValue is discouraged for SQLServer queries](https://www.dbdelta.com/addwithvalue-is-evil/) – Caius Jard Dec 01 '21 at 17:03

1 Answers1

1

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() ...
                ^^
Caius Jard
  • 72,509
  • 5
  • 49
  • 80