-2

(Sobbing out of frustration)

How do you avoid annoying NRE in this case? The output of the code is correct, but I wish to get rid of the NRE.

Background:

There are some buttons on a form, some of which represent seats of a classroom. The other buttons are irrelevant because I only need the seat buttons, and only the seat buttons have tags that has value.

So, I loop through all buttons and read their tags, if it is not empty, then keep that button in a list. The rest are ignored.

However, when the code is run, NRE pops up at the fourth line, the line starting with "try".

foreach (Button seatbutton in this.Controls)
 {
   string betta;
   try { betta = seatbutton.Tag.ToString(); }
   catch { betta = ""; }

   if (!string.IsNullOrEmpty(betta))
    {
     seatbuttons.Add(seatbutton);
    }
 }

This is the shortest, most straightforward example of this type of NRE in my code. There are several more.

I have searched the web, and most responses are among the lines of: "Bad coding habits caused this."

As you can probably tell, I'm quite new at this whole thing and haven't even had the time to build habits yet. Can you guys help? Perhaps with some tips for GOOD coding habits?

T_T thanks!

Momom0
  • 79
  • 1
  • 9
  • @MickyD Yes! I read that one before I asked :D. And I do understand that seatbutton.Tag is sometimes null. But what I don't get is why assigning that null value to a string variable cannot be done... Well, I clearly can, because that's what I've done in the "Catch" part... :S – Momom0 Jul 17 '16 at 04:19
  • 2
    @Momom0 That's not what you're doing. You're first calling `ToString()` on it, and you can't call method on a `null` reference. – Ken Wayne VanderLinde Jul 17 '16 at 04:21
  • _"why assigning that null value to a string variable cannot be done"_ - well you can but you can't then attempt to invoke an instance method on it. This isn't objective-c –  Jul 17 '16 at 10:42

1 Answers1

0

You need to check if the tag is null before you call the ToString() method on it. Something like this:

string betta = seatbutton.Tag == null ? "" : seatbutton.Tag.ToString();
if (betta == "") {
  seatbuttons.Add(seatbutton);
}

If you're using the latest VS/C#, then you can alternatively use the new operator:

string betta = seatbutton.Tag?.ToString();
if (!string.IsNullOrEmpty(betta)) {
  seatbuttons.Add(seatbutton);
}
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
  • Wow~ that was nice! Thanks! Never seen this syntax before but it works perfectly. And apparently, my other NREs were spawns of this one. Once you solved this one, all others were gone! THANKS! – Momom0 Jul 17 '16 at 05:06