1

I am coding in vb.net. At times the data is empty/null this is due to user's input into the db. i will like to bypass it, however i get no luck.

here is snippet of my code:

If hct.mydbvalue.name IsNot Nothing Then
   dr("mydbvalue") = hct.mydbvalue.name
End If

I still get an error:

System.NullReferenceException: Object reference not set to an instance of an object.

is there a way if it is a null value to not do anything?

4
  • Which line is the exception getting thrown on? Commented Aug 12, 2011 at 14:31
  • What are hct and mydbvalue? Commented Aug 12, 2011 at 14:31
  • Both hct and hct.mydbvalue being Nothing will generate this exception as well. You should treat that as a bug, not something to work around. Commented Aug 12, 2011 at 14:34
  • are you reading or writing data? my guess is that dr is a datareader. Commented Aug 12, 2011 at 14:36

11 Answers 11

2

Both @FishBasketGordo and @Yuck are correct, you need to check the full object path for nullability:

If (hct IsNot Nothing) AndAlso (hct.mydbvalue IsNot Nothing) AndAlso (hct.mydbvalue.name IsNot Nothing) Then
   dr("mydbvalue") = hct.mydbvalue.name
End If
Sign up to request clarification or add additional context in comments.

Comments

1

You won't get a NullReferenceException from data in the database that's null when using ADO.NET; ADO.NET uses DBNull.Value to represent null, so your null reference is coming from somewhere else. In the code above, your exception could occur if any of the following were null:

  • hct
  • hct.mydbvalue
  • dr

Comments

1

from VS14+ you can use

If hct?.mydbvalue?.name IsNot Nothing Then dr("mydbvalue") = hct.mydbvalue.name End If

Comments

0

Make sure that the whole chain is not null. If hct or mydbvalue is null, you'll get the exception.

Comments

0

To me this looks like hct.mydbvalue is null, and therefore you can't call "name" on it.

Comments

0
Private Function NullCheck(ByVal inObject As Object, Optional ByVal defaultValue As Object = "") As Object
    Dim out As Object
    If Not IsDBNull(inObject) Then
        out = inObject ' This returns the value that was passed in when it is not null
    Else
        out = defaultValue ' This ensures that out is something and defaults to ""
    End If
    Return out
End Function

3 Comments

IsDbNull() returns a Boolean value indicating whether an expression evaluates to the System.DBNull class. It does not test for null reference.
In fact I did write a test before writing the comment. In the example provided in the question if hct or hct.mydbvalue is null then NullReferenceException will be thrown when your NullCheck() method is called.
@TIM You did not double ding me for having omitted his hct , you double dinged me for using a boolean and it absolutely does test for null reference of the passed in object, which can be used to test hct or hct.mydbvalue.name and I would think if you understood code this would be obvious!
0

You should be checking whether hct is Nothing, as well as mydbvalue. If you look at the exception message property, it will tell you which is causing the error.

2 Comments

@Yuck Where in the exception will it tell you which object is nothing?
@Tim - You're right; it doesn't. Not sure why I was thinking that. If you debug you can get watch values for variables though and see which is null.
0

I'm also solving this problem, but in C#.

On my project we've complex object paths like "RootObject.childObject.LitleObject.TinyObject.StringName"

when any of these objects in the path is null, you'll get a null reference when you try something easy like

if(RootObject.childObject.LitleObject.TinyObject.StringName == "a")

I would be okay if it just works as whole rest of the path will be null.

eg. when childObject = null, then I want also RootObject.childObject.LitleObject.TinyObject.StringName to be null, not null reference exception.

However I've found no solution yet, but there is one new operator which can slightly help you in some null tasks.

a = object.object ?? defaultValue;

operator ?? is something like ISNULL in SQL server. If object on left is null, it returns the object from right.

It also replaces whole function NullCheck posted by Michael above.

Hope this will help a bit.

more info on operators http://msdn.microsoft.com/en-us/library/ms173224(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/6a71f45d(v=vs.80).aspx

Comments

0

you're talking about diferent things.

It doesn't matter if you use ISDBNull(x.y), String.IsNullOrEmpty(x.y) or (x.y=null)

The problem is far sooner than your selected function is called.

when X is null, it cannot have a property Y. so when you call

AnyOfYourPrefferedFunctions(x.y);

the error raises during evaluation of x.y (null. doesn't exist), so it stops before the machine actually knows what is the function you want to call.

Probably only way to check this, would be using reflection. But you would need to send string with path and reference to root. so something like:

var v = GetValueThroughReflection(rootObject, "rootObject.path.to.the.last.object");

Then you'll be able to write a function which will go through the object path and find which one is null and handle it accordingly. e.g. returns null.

But when you'll heavy use that function, it can make your application run slower. as you'll use reflection for such simple task as is getting value out of variable.

Comments

-1

Try inserting a IF NOT isdbnull(hct.mydbvalue.name)

4 Comments

Tried to edit this to expand on my initial thoughts but the save timed out...haha So I added a second answer
IsDbNull() returns a Boolean value indicating whether an expression evaluates to the System.DBNull class. It does not test for null reference.
My comment is a copy and paste from the help file and as I said in my comment to your other answer I did write test code before commenting and down voting.
@Tim You could not possibly have tested this
-1

The following code checks all values.

If hct IsNot Nothing AndAlso 
   hct.mydbvalue IsNot Nothing AndAlso
   Not String.IsNullOrWhitespace(hct.mydbvalue.name) Then

    dr("mydbvalue") = hct.mydbvalue.name

End If

Note that the last test used String.IsNullOrWhitespace(). I'm assuming name is a string and you don't want to save empty strings.

Update 1

The following code is a simple console application to prove that using IsDbNull() or Micheal's NullCheck() will throw NullReferenceException when hct.mydbvalue is Nothing.

Module Module1

    Sub Main()

        Dim hct = New hct
        Dim dr = New Dictionary(Of String, String)
        Dim errorCount = 0

        Try
            Dim thisCallWillFail = IsDBNull(hct.mydbvalue.name)

        Catch ex As NullReferenceException
            Console.WriteLine(
                "Using IsDBNull() threw NullReferenceException as expected."
            )
            errorCount += 1

        End Try

        Try
            Dim thisCallWillFail = NullCheck(hct.mydbvalue.name)

        Catch ex As NullReferenceException
            Console.WriteLine(
                "Using NullCheck() threw NullReferenceException as expected."
            )
            errorCount += 1

        End Try

        Console.WriteLine("errorCount = 2? {0}", errorCount = 2)

    End Sub

    Private Function NullCheck(ByVal inObject As Object, 
                               Optional ByVal defaultValue As Object = "") As Object

        Dim out As Object

        If Not IsDBNull(inObject) Then

            ' This returns the value that was passed in when it is not null
            out = inObject 

        Else

            ' This ensures that out is something and defaults to ""
            out = defaultValue 

        End If

        Return out

    End Function

End Module

Public Class hct
    Property mydbvalue As mydbvalue
End Class

Public Class mydbvalue
    Property name As String
End Class

3 Comments

@Tim Assuming that whitespace is not wanted is not warranted by the original question.
@Michael Given the question I made an assumption Menew is new to programming and thought an example using IsNullOrWhitespace() was prudent.
@Michael Does the code example I've now provided changed your opinion to my previous comments? If not what am I missing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.