Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

System.NullReferenceException for 1

Status
Not open for further replies.

Antzz

Programmer
Jan 17, 2001
298
US
Hi Everybody,
I am new to C# and am trying to develop a component for database access. I am writing a class object where I create new connection and command objects in the constructor and try to use those declared objects in different methods in the class. It goes something like this:

namespace <namespace>
{
public class DataObj
{
private SqlConnection oConn;
private SqlCommand oCmd;

public DataObj
{
SqlConnection oConn = new SqlConnection();
SqlCommand oCmd = new SqlCommand();
}

public void OpenConnection()
{
oConn.ConnectionString = <Connection str>;
oConn.Open();
oCmd.Connection = oConn;
}

}
}

I get an error in the OpenConnection method when trying to use oConn.Open. The error states that the object has not been instantiated.

Appreciate it

Antzz
 
The problem is with your constructor, firstly your have missed the brackets of the constructor name. Secondly and more importantly (as it is not pointed out be the sytax checker) by placing the type names in front of the variable names in the constructor your are decalring them as local variables so the members are not being set.

Code:
 public DataObj
     {
         //The extra type declerations mean that local variables were being declared
         //SqlConnection oConn = new SqlConnection(); 
         oConn = new SqlConnection(); 

         //SqlCommand oCmd = new SqlCommand(); 
         oCmd = new SqlCommand(); 
     }

Regards
 
Thanks a lot John. I was able to figure it our yesterday. But it makes more sense to me with your explanation. Apperciate it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top