3

Possible Duplicate:
What is a NullReferenceException in .NET?

For example, "System.NullReferenceException was unhandled", with Message "Object reference not set to an instance of an object."

What is the meaning of this exception, and how can it be solved?

Community
  • 1
  • 1

6 Answers6

14

It means you've tried to access a member of something that isn't there:

string s = null;
int i = s.Length; // boom

Just fix the thing that is null. Either make it non-null, or perform a null-test first.

There is also a corner-case here related to Nullable<T>, generics and the new generic constraint - a bit unlikely though (but heck, I hit this issue!).

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
8

This is the most common exception in .NET... it just mean that you try to call a member of a variable that is not initialized (null). You need to initialize this variable before you can call its members

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 1
    Note that this advice applies to "fields" (instance/static variables) - but not to local variables (definite assignment is applied to local variables; you can't even *attempt* to use an uninitialized local variable). – Marc Gravell Jun 23 '09 at 08:35
2

It means you're referencing something that's null, for example:

class Test
{

   public object SomeProp
   {
      get;
      set;
   }

}

new Test().SomeProp.ToString()

SomeProp will be null and should throw a NullReferenceException. This is commonly due to code you are calling expecting something to be there that isn't.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
1

That means that you have tried to use a method or property of an object, when the variable is not yet initialized:

string temp;
int len = temp.Length; // throws NullReferenceException; temp is null

string temp2 = "some string";
int len2 = temp2.Length; // this works well; temp is a string
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • For local variables (as per the example shown), it *is* initialized (otherwise it won't compile). Simply: it is initialized to null. – Marc Gravell Jun 23 '09 at 08:39
  • 1
    if 'temp' is a local variable it will _not_ compile. If it's a field it will be null. – H H Jun 23 '09 at 08:47
1

The code below will show you the exception, and a clue.

string s = null;
s = s.ToUpper();
H H
  • 263,252
  • 30
  • 330
  • 514
1

Somewhere in your code, you have an object reference, and it's not set to an instance of an object :)

Somewhere you've used an object without calling it's constructor.

what you should do:

MyClass c = new MyClass();

what you've done:

MyClass c;
c.Blah();
Matt Jacobsen
  • 5,814
  • 4
  • 35
  • 49