tags:

views:

30

answers:

2

I have this method:

Private Sub SetIfNotNull(ByVal input As Object, ByRef destination As Object, ByVal ConversionType As ConversionType)
        If input IsNot Nothing AndAlso input <> "" Then
            Select Case ConversionType
                Case DealerTrackConnection.ConversionType._String
                    destination = input
                Case DealerTrackConnection.ConversionType._Integer
                    destination = Convert.ToInt32(input)
                Case DealerTrackConnection.ConversionType._Double
                    destination = Convert.ToDouble(input)
                Case DealerTrackConnection.ConversionType._Date
                    destination = Convert.ToDateTime(input)
                Case DealerTrackConnection.ConversionType._Decimal
                    destination = Convert.ToDecimal(input)
            End Select
        End If
    End Sub

And here is one call in which it fails:

SetIfNotNull(ApplicantElement.Element("suffix").Value, NewApplicant.Suffix, ConversionType._String)

If the element from the XML file is nothing (there is no tag), the method call fails. but I am checking for nothing. Why is it doing this and how would I modify the code to fix it this time and everytime.

+2  A: 

The problem isn't in your SetIfNotNull method, rather it is in this piece of code: ApplicantElement.Element("suffix").Value

The element is null, so the Value call throws a NullReferenceException. Try this instead:

CType(ApplicantElement.Element("suffix"), String)

Also, you can consolidate the checks in this line:

If input IsNot Nothing AndAlso input <> "" Then

into this:

If Not String.IsNullOrEmpty(input) Then
Ahmad Mageed
+1 The checks can be consolidated further. In VB.Net `String.IsNullOrEmpty(input)` is equivalent to `(input = "")` because VB.Net treats `Nothing` like `""` when performing string comparisons with `=`. [See here](http://stackoverflow.com/questions/2633166/nothing-string-empty-why-are-these-equal/2633274#2633274)
MarkJ
@MarkJ thanks, I wasn't aware of that :)
Ahmad Mageed
A: 

It seems that ApplicantElement.Element("suffix") is nothing and therefor the exception occurs before your method is called, isn't it?

If Not ApplicantElement.Element("suffix") Is Nothing Then
    SetIfNotNull(ApplicantElement.Element("suffix").Value, NewApplicant.Suffix, ConversionType._String)
End If
Tim Schmelter