Logo 
Search:

C# Forum

Ask Question   UnAnswered
Home » Forum » C#       RSS Feeds

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

  Asked By: Danielle    Date: Apr 13    Category: C#    Views: 9096
  

I am getting following error message.

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

I am getting this error message more than others, and the cause is that a variable is used in code, but that variable
doesn't contain a reference to any object in memory.

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Rosie Hughes     Answered On: Apr 13

Cause for this error:
Error generally occur when you access a member of a reference  type variable  that is set  to null.

Error Solutions:
Check below error  cases why we are receiving null reference exception.

Error Case 1.
In this case,code is trying to access a member of a reference type variable that is set to null.
string str=null;
if (str.Length ==2)
{
Console.Write("Done");
}


Error Case 2.
public class clsArr
{
public int[] iArr;
}

public class clsTest
{
public static void Main()
{
clsArr objArr = new clsArr();
try
{
int i = objArr.iArr[0];
}
catch( NullReferenceException e )
{
Console.WriteLine( "Error: {0}.", e);
}
}
}


Other Cases:

Trying to invoke xml web service,if it is fails to create the proxy object  and throw the below exception.

Error Desc:
Object reference not set to an instance  of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Solution:
This generally means that something is declared without allocating memory  for it.

For instance, if you invoked the web service like this:

Dim oWS As WS.MyWebService
iData = WS.MyMethod()

then declare in this way.

Dim oWS As New WS.MyWebService
iData = WS.MyMethod()


Version: ASP.net 1.x

 
This post is locked for further answers.