-2

I'm getting System.NullReferenceException: Object reference not set to an instance of an object. Exception with below code.

   string avblCount = "0";

    if (!string.IsNullOrWhiteSpace(item.PART_AVAILABILITY.AVAIL_COUNT.ToString() as string))
    {
         avblCount = item.PART_AVAILABILITY.AVAIL_COUNT.ToString();
    }

Exception occurred from this line.

if (!string.IsNullOrWhiteSpace(item.PART_AVAILABILITY.AVAIL_COUNT.ToString() as string))

How can i fix this ?

Bishan
  • 15,211
  • 52
  • 164
  • 258
  • item.PART_AVAILABILITY.AVAIL_COUNT.ToString() as string) why ? do only as string it won't throw error – Kamil Budziewski Jul 05 '13 at 07:39
  • 2
    `item` or `CAPSLOCKHAPPYPROPERTY` is null, edit, why not just check if these are null instead of converting it to a string first? – Sayse Jul 05 '13 at 07:39
  • does every part of item.PART_AVAILABILITY.AVAIL_COUNT exist? What if for example PART_AVAILABILITY is null? – Paul Zahra Jul 05 '13 at 07:39
  • first tell tem.PART_AVAILABILITY.AVAIL_COUNT is the null ? – MANISHDAN LANGA Jul 05 '13 at 07:39
  • 3
    _"How can i fix this?"_ - by searching the web. There's thousands of questions on this error on SO alone. Try to understand what the error means. – CodeCaster Jul 05 '13 at 07:40
  • 2
    If you program in C# you absolutely positively must learn what a NullReferenceException is, how they come about, how they present themselves at runtime, how you can handle them, mitigate them and finally avoid them. – flq Jul 05 '13 at 07:46

1 Answers1

3

One or more of these entities are null:

  • item
  • item.PART_AVAILABILITY
  • item.PART_AVAILABILITY.AVAIL_COUNT

You should check which one is, and then act accordingly

LittleSweetSeas
  • 6,786
  • 2
  • 21
  • 26
  • Are you serious? If item is null, then the 3 are nulls. If item is not null but PART_AVAILABILTY is, then there are 2 nulls. If item and PART_AVAILABILTY aren't null, then AVAIL_COUNT is. – LittleSweetSeas Jul 05 '13 at 07:54
  • Exactly: they lead to a NullReferenceEx as per question. Is it just a flame or a dictionary-check? – LittleSweetSeas Jul 05 '13 at 07:56
  • Well, I won't argue nomore, but in my opinion if item is null, all its properties are "undefined": there is no "undefined" key-word in .NET, and obviously it has no sense to enter into reflection to check if a property is available in a given object. So, i used "null" in a unspecific way, but you're right: undeclared/undefined != null to a compiler eyes :) – LittleSweetSeas Jul 05 '13 at 08:08