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?

0

6 Answers 6

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!).

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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).
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.

2 Comments

If o is a local variable, this won't compile. Unassigned local variables are not null.
You're right. Changed the example.
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

2 Comments

For local variables (as per the example shown), it is initialized (otherwise it won't compile). Simply: it is initialized to null.
if 'temp' is a local variable it will not compile. If it's a field it will be null.
1

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

string s = null;
s = s.ToUpper();

Comments

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();

2 Comments

Which won't compile... (definite assignment)
You're right, and they won't have my implementation of MyClass either. Let's do Random r = null; r.Next(); instead then.