Why do I get the error "Object reference not set to an instance of an object"?
The code is trying to access a member of a reference type variable that is set to null.
Given the following class, let's examine some code that could be in the Main method:
using System;
class Foo
{
static void Main()
{
// foo has not been instantiated
Foo foo = null;
// implementation to be discussed...
}
public int BarProperty
{
get { return 0; }
}
public string BarMethod()
{
return null;
}
}
Looking at Main, notice that foo is set to null. Your situation will not be this explicit because the variable you are trying to use could be a class field, parameter, or local variable that was once instantiated but was subseqently set to null. Given that foo is null, the following code will throw a NullReferenceException:
try
{
// foo is null, and you can't call
// BarProperty on null.
int resultBad = foo.BarProperty;
}
catch (NullReferenceException nre)
{
Console.WriteLine(
"\nCan't read BarProperty, foo is null.\n" +
nre.Message);
}
Since foo is null, you can not use its members. This was a property, but the following code demonstrates calling a method:
try
{
// foo is null, and you can't call
// BarMethod on null.
foo.BarMethod();
}
catch (NullReferenceException nre)
{
Console.WriteLine(
"\nCan't call BarMethod(), foo is null.\n" +
nre.Message);
}
The code above throws a NullReferenceException because foo is still null. It doesn't matter that the first call was a property and the second is a method - they are both members of the type.
Now, to fix this problem, you must ensure that foo is instantiated before it is used. The following code instantiates foo and the previous problems are solved:
// now we have an instance
foo = new Foo();
// works fine
int resultGood = foo.BarProperty;
Since foo now refers to a valid instance, the code can call any of its members. This was easier than many null reference problems. Sometimes you have multiple levels of indirection, leaving you with a scenario you didn't expect. Assuming that foo now references an object, there is still a problem with the following code:
try
{
// still breaks because BarMethod() returned
// null and you can't call Trim() on null.
foo.BarMethod().Trim();
}
catch (NullReferenceException nre)
{
Console.WriteLine(
"\nCan't call Trim(), BarMethod() returns null.\n" +
nre.Message);
}
The problem occurs in the code above because BarMethod returned null, which means that the code is trying to call the Trim method on a string reference that is set to null.
The proper way to fix this problem is to debug BarMethod to find out why it returned null. That assumes BarMethod is not supposed to return null. If, in your application, it made sense for BarMethod to sometimes return null, then you would have to check the return value of BarMethod before you called any members of the return value.
[Author: Joe Mayo]
Anonymous
May 07, 2004
I really hate to ask this question, but do people really ask THAT question (for code written like this?) Call me a nay-sayer, but this seems a little, well.. obvious, now doesn't it?Anonymous
May 07, 2004
The question and the problem comes in many different forms. To me, picking just one scenario may not be descriptive of the cause of the problem. So, I approached it in a generic way. The subject contains text from the message that appears when a NullReferenceException is thrown, which I felt would be identifiable for someone looking for and answer to this problem in the FAQ. Google gives me over 5,000 entries on "NullReferenceException". The description explains why this type of problem happens. It is designed for the reader to be able to draw a parallel between the explanation and their own problem. While the message and description is obvious to the majority of C# developers, it is not to many beginners who have only a vague idea of what an object or reference is in the first place. I certainly respect your point-of-view and understand that some people prefer to see content targeted at their level of understanding. Do you think this should have the title modified, content modified, or removed?Anonymous
May 07, 2004
Brady, just take a look at the microsoft.public.dotnet newsgroups... it sounds incredible but I swear we get at least one such post per week! "Null reference exception... help, what's happening, what's that, what am I doing wrong!?"
People who are new to managed code apparently simply don't understand this message, and since it's generated by .NET they assume there must be a problem with .NET (and not with their program).
So I think this log entry and its title are appropriate, I only worry that the target audience that doesn't know about object references won't know about this blog either... but at least we can post a link on the MS newsgroups now. :-)Anonymous
May 13, 2004
Though it's been a while, I can still remember pondering that error. When you mainly have done languages which do not have even simple objects, the meaning of object instances will take a while to grasp.
It could be good idea to have a easily noticeable and clickable link in the error message which points to a help file with an explanation that has been proven to be understandable to a person who never heard of objects, and that help file would also carry link to some OO-basics place.Anonymous
May 26, 2004
Good post! I will definitely point people to it the next 1000 times I get asked such a question! :)
On a side-note, I worry that new developers looking at the code will merely latch-on to the way your Try/Catch is written and add an exception-filter for NullReferenceException. This is a prime candidate for using exceptions and try/catch as flow-control, which is explicitly prohibited by almost every coding standard.
You might consider just commenting where the exception would occur, rather than including that exception filter.
ThanksAnonymous
July 06, 2004
The comment has been removedAnonymous
July 14, 2004
I'm having the same problem. I'm using an accessor, I've instantiated the variable, but i still the get the null reference.Anonymous
July 21, 2004
I've been programming in OO languages for many years now. But I'm new to C# and trying to call functions from a DLL. I'm getting this message and can't figure out why. Here's the code:
using System;
using System.Runtime.InteropServices;
namespace PiApi {
public class clsPiApi {
[DllImportAttribute("piapi32.dll", EntryPoint="pipt_findpoint", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall )]
public static extern int findpoint([MarshalAsAttribute(UnmanagedType.LPStr)] string TagName ,
[MarshalAsAttribute(UnmanagedType.I4)] int pt);
public int getPoint(string TagName) {
int ptno = new int();
int retVal = new int();
try {
retVal = findpoint(TagName, ptno);
} catch(System.NullReferenceException e) {
System.Console.Write("Error " + e.Message + "nn");
}
if(retVal == 0){
return ptno;
} else {
return 0;
}
} // end of getPoint
} // end of class
} // end of namespace
namespace Test {
using PiApi;
public class MyTest {
public static int Main(){
clsPiApi objPI = new clsPiApi();
System.Console.Write("Tag for pipt FIC3499.MD is {0}.n", objPI.getPoint("FIC3499.MD"));
return 0;
}
}
}
Any ideas?Anonymous
August 06, 2004
The comment has been removedAnonymous
October 19, 2009
I always meet this exception:)Anonymous
December 03, 2009
using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web .Configuration ; using System.Data .SqlClient ; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; public partial class Default2 : System.Web.UI.Page { public string connection = WebConfigurationManager.AppSettings["pubs1"].ToString(); SqlConnection cnew = new SqlConnection(ConfigurationManager.AppSettings["pubs1"].ToString());// new SqlConnection(); SqlCommand cmd = new SqlCommand(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bindgrid(); } } void bindgrid() { List <company> item=new List <company>(5); for(int i=0;i<5;i++) { company c=new company (); item.Add (c); } GridView1.DataSource = item; GridView1.DataBind(); } protected void clearButton_Click(object sender, EventArgs e) { bindgrid(); } void beginadd() { //SqlConnection cnew = new SqlConnection(connection); //SqlCommand cmd = new SqlCommand(); cnew.Open(); SqlTransaction tran = cnew.BeginTransaction(); cmd.Connection = cnew; cmd.Transaction = tran; cmd.CommandText = "insert into msm_company(comp_id,comp_name)values (@companyid,@companyName"; SqlParameter p1 = new SqlParameter("@companyid", SqlDbType.VarChar); SqlParameter p2 = new SqlParameter("@companyName", SqlDbType.VarChar); cmd.Parameters.Add(p1); cmd.Parameters.Add(p2); //cnew.Close(); } void addcustomer(string companyid,string companyname) { try { //cnew.Open(); cmd.Parameters[0].Value = companyid; cmd.Parameters[1].Value = companyname; cmd.ExecuteNonQuery(); } catch { cmd.Transaction .Rollback (); } } void completeadd() { try { //cmd.Transaction.Commit(); Label1.Text = "record added successfully"; } catch (Exception ex) { Label1.Text = "error inserting record"; Label1.Text += ex.Message; } finally { cnew.Close(); } } protected void saveButton_Click(object sender, EventArgs e) { beginadd(); foreach (GridViewRow row in GridView1.Rows) { if (row.RowType == DataControlRowType.DataRow) { string companyid = ((TextBox)row.FindControl("textbox1")).Text; string companyname = ((TextBox)row.FindControl("textbox2")).Text; if (companyid != "") { addcustomer(companyid, companyname); } } } completeadd(); } } this is my code.Why do I get the error "Object reference not set to an instance of an object"?Anonymous
April 14, 2011
So............what do I have to do in order not to receive the message prompt. How do I fix it. If I can bypass this without having to consult our IT guys it will be awesome TXAnonymous
July 11, 2011
Unbelievable. So for those who found this page via Google, the best place to get the answer to your question is here: en.csharp-online.net/CSharp_FAQ:_What_does_Object_reference_not_set_to_an_instance_of_an_object_mean I really enjoy how the first responder sarcastically responds in know-it-all fashion without explaining anything to anyone, then his friends chime in and say it comes up a lot, then 7 years of the same question go by and NO ONE EVER ANSWERS IT! Sheesh!Anonymous
July 12, 2011
[NullReferenceException: Object reference not set to an instance of an object.] mssqlonly_clone.Web.UI.PlayerSettings.btn_show_Click(Object sender, EventArgs e) +166 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563Anonymous
August 24, 2011
The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:
- Add a "Debug=true" directive at the top of the file that generated the error. Example: <%@ Page Language="C#" Debug="true" %> or:
- Add the following section to the configuration file of your application: <configuration> <system.web> <compilation debug="true"/> </system.web> </configuration> Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode. Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario. Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.] Admin_passward_login.Button1_Click(Object sender, EventArgs e) +205 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
Anonymous
February 05, 2012
if (e.CommandName == "Accept") { int id = Convert.ToInt32(e.CommandArgument); pnlOrderDetail.Visible = true; DCOrderDetialClass dco= new DCOrderDetialClass(); dco = D2DConfirmOrder.getDcOrderDetail(id); txtOrderType.Text = dco.OrderType; txtOrderStatus.Text = dco.OrderStatus; txtInvoiceNumber.Text = dco.InvoiceNumber.ToString(); txtDate.Text = dco.Date.ToShortDateString(); txtSourceDealer.Text = dco.SourceDealer; } Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 115: DCOrderDetialClass dco= new DCOrderDetialClass(); Line 116: dco = D2DConfirmOrder.getDcOrderDetail(id); Line 117: txtOrderType.Text = dco.OrderType; Line 118: txtOrderStatus.Text = dco.OrderStatus; Line 119: txtInvoiceNumber.Text = dco.InvoiceNumber.ToString();Anonymous
September 05, 2012
- string qry = "select pay_date,stu_id,stu_name,coll_name,amt_paid from payment where stu_id="+ Convert.ToInt32(textBox1.Text); 2 da = new SqlDataAdapter(qry,con); 3 dt = new DataTable(); 4 da.Fill(dt); 5 dataGridView1.DataSource = dt; 6 dataGridView1.Columns["pay_date"].HeaderText = "PAYMENT DATE"; 7 dataGridView1.Columns["stu_id"].HeaderText = "STUDENT ID"; dataGridView1.Columns["stu_name"].HeaderText = "STUDENT NAME"; 8 dataGridView1.Columns["coll_name"].HeaderText = "NAME OF THE COLLEGE "; 9 dataGridView1.Columns["amt_paid"].HeaderText = "PAID AMOUNT "; i got oject reference not set to an instance error in the line no.6
Anonymous
September 17, 2012
The comment has been removedAnonymous
September 19, 2012
I prepared .exe file for wpf application and installed in my computer........................while using that application i am getting the error "object reference not set to an instance" pls send me the solution for this errorAnonymous
May 22, 2013
I am New to .Net Technology in my project when I search something in my database using search button the same exception occur Here is my Search button code DataTable dt = new DataTable(); Setup s = new Setup(); Grid_Trans_Search.DataSource = s.Get_Tranc_Master_Search(txt_Trans_Type_Desc_Search.Text); Grid_Trans_Search.DataBind(); panel_gdview.Visible = false; panel_gdview_Search.Visible = true; And Calling Store data procedure public DataTable Get_Tranc_Master_Search(string Transection_Type_Desc) { SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@Transection_Type_Desc", Transection_Type_Desc); DataAccessLayer da = new DataAccessLayer(); DataSet ds = da.getDataByParam(param, "[Get_Tranc_Master_Search]"); return ds.Tables[0]; } how can I find out the solutionAnonymous
July 29, 2013
Please help me, i get this problems to. Form2 frm2; // what is code to generate instance except frm2 = new Form2(); // can i use other code to generate instance, like this example frm2.CreateInstance("System.Windows.Form") frm2.Show();Anonymous
March 11, 2014
The comment has been removedAnonymous
May 05, 2014
<pre lang="cs">FPTS_PROPERTY p = new FPTS_PROPERTY(); //FPTS_PROPERTY q = new FPTS_PROPERTY(); p.pro_part_no =dp_part1.SelectedValue.ToString(); p.pro_machine_id =dp_machine1.SelectedValue.ToString(); FPTS_METHOD m = new FPTS_METHOD(); ds = m.FUN_GET_CYCLETIME(p); lb_cycletime1.Text = ds.Tables["MACHINE_MST"].Rows[2].ToString();</pre> i get error: <pre>Object reference not set to an instance of an object.</pre> please help me as soon as possibleAnonymous
February 04, 2015
The comment has been removedAnonymous
June 04, 2015
Please can someone help me out with the following lines of codes that throws: System.NullReferenceException: Object reference not set to an instance of an object. Public Sub createGrid_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles createGrid.Click Dim watershedLayer As MapWindow.Interfaces.Layer Dim watershedLayerHandle As Integer = Utilities.GetWatershedLayerHandle() ' If Not (watershedLayer Is Nothing) Then If mw.Layers.IsValidHandle(watershedLayerHandle) Then watershedLayer = mw.Layers.Item(watershedLayerHandle) Else If (findWatershedShapefile.ShowDialog = Windows.Forms.DialogResult.Cancel) Then Exit Sub UpdateWatershedPath(findWatershedShapefile.FileName) Dim layerName As String = "Watershed (" + System.IO.Path.GetFileName(WatershedShapePath) + ")" watershedLayer = mw.Layers.Add(WatershedShapePath, layerName) 'watershedLayer.Name = layerName End If 'End If ' Since this is "Create" grid it uses Nothing as the Grid layer so that GridForm will create one from scratch. gridForm = New MWAGNPSLib.GridForm(mw, watershedLayer, Nothing) gridForm.Show() End SubAnonymous
July 17, 2015
Exception: An error occurred during the operation of a service method: Object reference not set to an instance of an object. I got this error in metalogix please help meAnonymous
September 06, 2015
Pls check below script I want to move rename & delete files IF EXIST \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Balances_Real-Time_.xls COPY \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Balances_Real-Time_.xls \tstbamm1g$XL_Recon_TESTxlcap_Cash_Ledger_Balances_Real-Time_.xls IF EXIST \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Statement_Real-Time_.xls COPY \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Statement_Real-Time_.xls \tstbamm1g$XL_Recon_TESTxlcap_Cash_Ledger_Statement_Real-Time_.xls IF EXIST \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Balances_Real-Timeall_.xls COPY \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Balances_Real-Timeall_.xls \tstbamm1g$XL_Recon_TESTxlcap_Cash_Ledger_Balances_Realall-Time_.xls IF EXIST \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Statement_Real-Timeall_.xls COPY \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Statement_Real-Timeall_.xls \tstbamm1g$XL_Recon_TESTxlcap_Cash_Ledger_Statement_Real-Timeall_.xls IF EXIST \tstbamm1g$XL_DATA_TESTxlcapHoldings_Recon_.csv COPY \tstbamm1g$XL_DATA_TESTxlcapHoldings_Recon_.csv \tstbamm1g$XL_Recon_TESTxlcapHoldings_Recon_.csv Del \tstbamm1g$XL_DATA_TESTxlcapHoldings_Recon_.csv Del \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Statement_Real-Timeall_.xls Del \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Balances_Real-Timeall_.xls Del \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Statement_Real-Time_.xls Del \tstbamm1g$XL_DATA_TESTxlcap_Cash_Ledger_Balances_Real-Time_.xls REN \tstbamm1g$XL_DATA_TESTME*.csv ME*.txt REN \tstbamm1g$XL_DATA_TESTxlcap1HoldingsPrcCustom_.csv xlcap1HoldingsPrcCustom_.txt REN \tstbamm1g$XL_DATA_TESTxlcap2HoldingsPrcCustom_.csv xlcap2HoldingsPrcCustom_.txt REN \tstbamm1g$XL_DATA_TESTxlcap3HoldingsPrcCustom_.csv xlcap3HoldingsPrcCustom_.txt FOR /F %%a IN (\tstbamm1g$XL_DATA_TESTLIST.TXT) DO MOVE \tstbamm1g$XL_DATA_TEST%%a \tstbamm1g$XL_DATA_TESTMMDDYYYY%-%%a DEL \tstbamm1g$XL_DATA_TESTLIST.TXT IF /I EXIST \tstbamm1g$XL_DATA_TESTxlcap1sedol_CAMRA_Interface_Trade_Feed_Download_-Standard~.txt MOVE /Y \tstbamm1g$XL_DATA_TESTxlcap1sedol_CAMRA_Interface_Trade_Feed_Download_-Standard~.txt \tstbamm1g$XL_DATA_TEST%MMDDYYYY%-xlcap1sedol_CAMRA_Interface_Trade_Feed_Download_-Standard~.txt IF /I EXIST \tstbamm1g$XL_DATA_TESTxlcap2sedol_CAMRA_Interface_Trade_Feed_Download_-Standard~.txt MOVE /Y \tstbamm1g$XL_DATA_TESTxlcap2sedol_CAMRA_Interface_Trade_Feed_Download_-Standard~.txt \tstbamm1g$XL_DATA_TEST%MMDDYYYY%-xlcap2sedol_CAMRA_Interface_Trade_Feed_Download_-Standard~.txt REN \tstbamm1g$XL_DATA_TESTXLCAPOUCashStatement*.csv XLCAPOUCashStatement*.txtAnonymous
October 12, 2015
Object reference not set to an instance of an object.Anonymous
October 12, 2015
Object reference not set to an instance of an object.Anonymous
December 28, 2015
Imports System.Data.SqlClient Public Class Form1 Dim cn As New SqlConnection("Data Source=DERICK;Initial Catalog=palm database;Integrated Security=True") Dim cmd As SqlCommand Dim dr As SqlDataReader Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load cn.ConnectionString = "Data Source=DERICK;Initial Catalog=palm database;Integrated Security=True" loadlistbox() End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If txtid.Text <> "" And txtname.Text <> "" And txtemail.Text <> "" And txtphone.Text <> "" And txtres.Text <> "" And txtentry.Text <> "" Then cn.Open() cmd.CommandText = "insert into (id,name,email,phone,address,entry date)values('" & txtid.Text & "','" & txtname.Text & "','" & txtemail.Text & "','" & txtphone.Text & "','" & txtres.Text & "','" & txtentry.Text & "')" cmd.ExecuteNonQuery() cn.Close() txtid.Text = "" txtname.Text = "" txtemail.Text = "" txtphone.Text = "" txtres.Text = "" txtentry.Text = "" loadlistbox() End If End Sub Private Sub loadlistbox() ListBox1.Items.Clear() ListBox2.Items.Clear() ListBox2.Items.Clear() ListBox3.Items.Clear() ListBox4.Items.Clear() ListBox5.Items.Clear() ListBox6.Items.Clear() cn.Open() cmd.CommandText = "select id, name,email,phone, address, entry date from info " dr = cmd.ExecuteReader() If dr.HasRows Then While (dr.Read()) ListBox1.Items.Add(dr("id")) ListBox2.Items.Add(dr("name")) ListBox3.Items.Add(("email")) ListBox4.Items.Add(("phone")) ListBox5.Items.Add(("Address")) ListBox6.Items.Add(("Entry date")) End While End If End Sub Private Sub ListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseClick Dim lb As New ListBox lb = sender If lb.SelectedIndex <> -1 Then ListBox1.SelectedIndex = lb.SelectedIndex ListBox2.SelectedIndex = lb.SelectedIndex ListBox3.SelectedIndex = lb.SelectedIndex ListBox4.SelectedIndex = lb.SelectedIndex ListBox5.SelectedIndex = lb.SelectedIndex ListBox6.SelectedIndex = lb.SelectedIndex End If End Sub End Class //solve for me the error