CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jeffrey Palermo [MVP]

Software management consultant and CTO, Headspring Systems

How to understand System.NullReferenceException, Object reference not set to an instance of an object - level 200

You probably get 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.  If you try to call .ToString() on an object, and your variable is null, you'll get this exception.  Sometimes it can be hard to figure out what's going on, but if you look at your stack trace, you can find out what method this Exception came from.  Then, debug through that method and find the offending variable. 

Likely causes are methods that take arguments but don't validate them.  If you accept an object as an argument, and you need the "Name" property from the object, you'll get this exception if "null" was passed in instead of a valid object instance.  If would be wise to add argument validation to the beginning of every method that may have callers you don't completely trust.  Err on the side of caution.  Code defensively.  Input is evil.  If your arguments pass validation (ensuring they aren't null is a common validation), you'll likely minimize the frequency of this nasty exception.

You likely won't get much love from Google when searching on this exception because the root cause is different in every scenario.  There's no "magic" code snippet that will make this puppy go away.  Understand the code and properly validate, and you'll sleep better, and your code will be more robust.



Comments

Raymond Lewallen said:

Awhile back I also wrote about 3 common causes that I usually see as culprits for this exception: http://codebetter.com/blogs/raymond.lewallen/archive/2005/06/23/65033.aspx
# August 19, 2005 7:12 AM

rerr said:

ttrtttt

# December 25, 2006 2:10 PM

hello said:

nice article

# March 22, 2008 1:56 PM

About Jeffrey Palermo

Jeffrey Palermo is a software management consultant and the CTO of Headspring Systems in Austin, TX. Jeffrey specializes in Agile coaching and helps companies double the productivity of software teams. Jeffrey is an MCSD.Net , Microsoft MVP, Certified Scrummaster, Austin .Net User Group leader, AgileAustin board member, INETA speaker, INETA Membership Mentor, Christian, husband, father, motorcyclist, Eagle Scout, U.S. Army Veteran, and Texas A&M University graduate. Check out Devlicio.us!

This Blog

Syndication