View Single Post
  #25 (permalink)  
Old 09-22-2007, 05:43 AM
oxygen oxygen is offline
D-Web Architect
 
Join Date: Jun 2007
Posts: 633
oxygen is on a distinguished road
Default Re: C# .Net Tips & Tricks

Object reference not set to an instance of an object error:

Considering the large number of "Object reference not set to an instance of an object" errors abound..

Cause one:

Not declaring variables!

Yes, I know it sounds obvious, but MAKE SURE that you've explicity declared the variable, and don't forget to use the appropriate scope!

One common mistayke is when working with Codebehind Classes, consider:

ASP.Net Codebehind Class
Code:

Public Class PageOne: System.Web.UI.Page

String strHello;
protected void Page_Load(object sender, EventArgs e)

strHello = "Hello!"
varOne.Text = strHello
End Sub

End Class


Remember! Codebehinds arn't handled the same way as inline/<script> pages!

You need to declare EVERY control you want to interact with in the codebehind class


Cause 2: Bad scoping!

Indeed...

One common cause is this:
Code:

protected void Page_Load(object sender, EventArgs e)

String strHello;


This won't work because strHello is accessible only by Sub Page_Load

Bad inits/constructs
Remember, some classes have constuctors

Consider DirectoryInfo:

Code:

Sub Page_Load()
{

System.IO.DirectoryInfo dirInfo;

dirInfo.GetDirectory("C:\");

}



In the above example, we've only defined dirInfo *AS* a DirectoryInfo class, we haven't actually created it

So we need to do this instead:

Code:

Sub Page_Load() ....

System.IO.DirectoryInfo dirInfo;

dirInfo = New System.IO.DirectoryInfo("C:\");
__________________
The OXYGEN
Delivers edgy, intelligent Technology to all...
Reply With Quote