-1

My Code:

basketsub.Properties.ColorId = Convert.ToInt32(itemspliters[3] != null 
  ? itemspliters[3].ToString() 
  : "0");

Error:

Object reference not set to an instance of an object!!!

Can you tell me what am I doing wrong? Thanks.

Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186
  • 1
    Have you debugged the code in your IDE of choice to determine which of the many members in that line of code is null? – Martin Costello Feb 19 '19 at 09:39
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See [mcve]. – Enigmativity Feb 19 '19 at 09:41
  • Check `itemspliters`, `basketsub`, `basketsub.Properties` is any of them `null`? – Dmitry Bychenko Feb 19 '19 at 09:42
  • This code will through an NRE if the array itself is empty. You should ensure the values *aren't* empty to begin with, instead of trying to handle nulls. The code needs quite a bit of cleaning too. If `itemspliters` contains strings, `ToString()` isn't needed. If not, what *does* it contain? – Panagiotis Kanavos Feb 19 '19 at 09:45
  • In any case you can use the null propagation operator to safely get the value and not even attempt to convert if there's a problem, eg `var value=itemspliters?[3]?.ToString(); basketsub.Properties.ColorId=(value==null)?0:int.Parse(value);` – Panagiotis Kanavos Feb 19 '19 at 09:48

1 Answers1

1

You should also check itemspliters != null

basketsub.Properties.ColorId = Convert.ToInt32(itemspliters != null && itemspliters.Length >= 4 && itemspliters[3] != null 
  ? itemspliters[3].ToString() 
  : "0");
Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48