The Artima Developer Community
Sponsored Link

.NET Buzz Forum
System.NullReferenceException - Object not set to an instance of an object. 3 common causes in...

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Raymond Lewallen

Posts: 312
Nickname: rlewallen
Registered: Apr, 2005

Raymond Lewallen is a .Net developer and Sql Server DBA
System.NullReferenceException - Object not set to an instance of an object. 3 common causes in... Posted: Jun 23, 2005 7:13 AM
Reply to this message Reply

This post originated from an RSS feed registered with .NET Buzz by Raymond Lewallen.
Original Post: System.NullReferenceException - Object not set to an instance of an object. 3 common causes in...
Feed Title: Raymond Lewallen
Feed URL: /error.htm?aspxerrorpath=/blogs/raymond.lewallen/rss.aspx
Feed Description: Patterns and Practices, OOP, .Net and Sql
Latest .NET Buzz Posts
Latest .NET Buzz Posts by Raymond Lewallen
Latest Posts From Raymond Lewallen

Advertisement

Every once in awhile, you come across this exception: System.NullReferenceException – “Object reference not set to an instance of an object.”  You see people asking about this everywhere; about why are they getting this error.  Below are a few common causes for this.

1. In VB.Net, you are trying to access a string that has not been initialized.  In C#, this isn’t possible.  You can’t even compile code like the following in C#

C# won't compile this

                        private void TestString()

                        {

                                    string a;

                                    if (a.Length == 0)

                                    {

                                                Console.WriteLine("Yes");

                                    }

                        }

However, in VB.Net, you can compile the equivalent, and that lead right down a road to the mentioned exception.

VB will compile, but throw a runtime exception.

    Private Sub TestString()

        Dim a As String

        If a.Length = 0 Then

            Console.Write("Yes")

        End If

    End Sub 

Remember, a string is a reference type (a character array) that has to have a value.  You don’t have to use the “new” keyword, but by default the value is Nothing/null.  You would have to at least initialize to a = String.Empty, or to some other actual value, before it will compile in C#, or run without exception in VB.Net

2. You never created a new instance of an object.  Again, this is code that C# will not compile, but VB.Net will, and throw a runtime error.  Same as a string, any reference type must be initialized.  Strings, DateTimes and some other CTS types have a misconception of being value types, like Integers, and they are not.

C# will not compile.

                        private void TestObject()

                        {

                                    ArrayList b;

                                    b.Add("Hello");

                        }

Here is the VB equivalent, that will compile, but throw the mentioned exception.

VB will compile but throw an exception.

    Private Sub TestObject()

        Dim b As ArrayList

        b.Add("Hello")

    End Sub

3.  You created the object, but killed it too soon.  Here is a simple example of that.

Don't kill objects too soon.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        TestObject()

        ShowCount()

    End Sub

 

    Dim b As New ArrayList

 

    Private Sub TestObject()

        b.Add("Hello")

        b = Nothing

    End Sub

 

    Private Sub ShowCount()

        Console.Write(b.Count.ToString())

    End Sub

A more complex example would be that you disposed of a class that maybe you use to access the database.  This killed the connection and command objects.  But then, somewhere else, you tried to call a method of that class that used those objects that no longer exists.  Again, same exception gets thrown, but coming from withing the instantiated class itself.

c = a.GetOrders() will throw an exception.

Public Class Class2

 

    Dim a As New MyDataAccessObjects.Customers

    Public Sub New()

        LoadData()

        LoadMoreData()

    End Sub

 

    Private Sub LoadData()

        Dim b As New Collection

        Try

            b = a.GetCustomers()

        Finally

            a.Dispose()

        End Try

    End Sub

 

    Private Sub LoadMoreData()

        Dim c As New Collection

        Try

            c = a.GetOrders()

        Finally

            a.Dispose()

        End Try

    End Sub

 

End Class 

The GetOrders function inside of Customers requires an instance of a connection, but you disposed of the required objects required to access the database back up in LoadData() when you called a.Dispose().  Be careful when you clean up your instances, that you are not using them again somewhere.  This is most common in classes where you are using class-wide instantiated objects.  If you create and drop your objects within each method, this isn’t going to be a problem, and you are actually following a better guideline by creating at the last necessary moment, and destroying at the first possible moment, not to mention avoiding possible exceptions like InvalidReferenceException.

Read: System.NullReferenceException - Object not set to an instance of an object. 3 common causes in...

Topic: TechEd 2005, Chennai Previous Topic   Next Topic Topic: Rory Blyth on bad UI design

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use