I\'m sure we all have received the wonderfully vague \"Object reference not set to instance of an Object\" exception at some time or another. Identifying the object that is
The line # and file are usually all you need to find the culprit. If you are the one throwing the exception, consider using an ArgumentNullException
, if appropriate, or checking for nulls and throwing NullReferenceException
s that have more details about the null field.
Edit @ your edit :)
AFAIK, you would have to examine the stack trace string to get that line # and file. Your best bet would be to get the innermost exception, and then look at the first line of its stack trace. If you want to be able to programatically parse that information to find out which field caused the null, and do something with that field's name, I fear you will be out of luck.
@W. Craig Trader
Good point. For a null value that is passed into the method, an ArgumentNullException
should be thrown. For a member variable that has not yet been initialized, something like an InvalidStateException
would probably be good to throw. Unfortunately, I can't find any such exception in MSDN. Roll your own?