开发者

Preparing for "nothing" in VB.NET method

开发者 https://www.devze.com 2023-01-22 02:16 出处:网络
I have this method: Private Sub SetIfNotNull(ByVal input As Object, ByRef destination As Object, ByVal ConversionType As ConversionType)

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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消