0

I was getting a null reference exception on the following line

VATinsrcommision  = _input_articletranstax
    .ARTEAMNTTRANTAX
    .Find(p => 
         p.TAXTYPECDE == TaxType.VAT_GST.GetStringValue())
    .TAXAMT;    

So I wrote this :

var VAT = _input_articletranstax
    .ARTEAMNTTRANTAX
    .Find(p => 
         p.TAXTYPECDE == TaxType.VAT_GST.GetStringValue());

if (VAT != null)
  VATinsrcommision = VAT.TAXAMT;

I want to know how can I do this in a better way

Eugene Podskal
  • 9,882
  • 5
  • 29
  • 51
user134235
  • 31
  • 4
  • 2
    There's nothing wrong with that. You're now using a null check for more defensive code, that's how it should be. –  Oct 14 '14 at 10:19
  • This is the best way. – Renatas M. Oct 14 '14 at 10:19
  • If it were me (and I'm nit-picking), I'd maybe just evaluate `VATinsrcommision`) without the involvement of another 'temporary' variable (`VAT`). I'm assuming you want to do something with `VATinsrcommision` but according to this bit of code it could still be null, so just test it later on when it's needed as you'll have to anyway. –  Oct 14 '14 at 10:20
  • Like in LINQ query we can write like this: (from o in m_SelectedPayabes where o != null select o.PBLE.PAYABLEID).Contains(payable.PBLE.PAYABLEID) So I want to know can we something like this for generic collection? – user134235 Oct 14 '14 at 10:21
  • Possibly, yes, but how are we meant to know what types you're working with? Even with LINQ, you're going to end up with a value that's null or not. So you need to check for that. Which is what you're doing anyway. So I don't see what you want to improve on. –  Oct 14 '14 at 10:23
  • OK. thanks for help. Maybe this ok. – user134235 Oct 14 '14 at 10:26
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Albireo Oct 14 '14 at 12:06

0 Answers0