Best way to handle NullReferenceExceptions in C #

Recently, I had a coding error in which, under certain conditions, the variable was not initialized, and I received NullReferenceException. This took a while to debug, because I had to find the bits of data that would generate this in order to recreate this error message, since the exception did not give the variable name.

Obviously, I could check each variable before use and throw an informative exception, but is there a way to do this better (read less)? Another thought I had was delivering with files pdbso that the error information contained a line of code that caused the error. How do other people avoid / deal with this problem?

thank

+5
source share
5 answers

First: do not do too much in one statement. If you have a huge number of dereferencing operations on one line, it will be much more difficult for you to find the culprit. Demeter’s law also helps with this - if you have something like order.SalesClerk.Manager.Address.Street.Lengththat, then you have many opportunities to get through when you get an exception. (I am not dogmatic about the Law of Demeter, but all in moderation ...)

Secondly: prefer casting using asunless it is not valid so that the object is of a different type, which usually includes a zero check right after that. So here:

// What if foo is actually a Control, but we expect it to be String?
string text = foo as string;
// Several lines later
int length = text.Length; // Bang!

NullReferenceException , , text null, , , foo null . , string, :

string text = (string) foo;

.

-: , - , API. Noda Time, , . , ( Period):

internal LocalInstant AddTo(LocalInstant localInstant,
                            CalendarSystem calendar, int scalar)
{
    Preconditions.CheckNotNull(calendar, "calendar");
    ...
}

, null.

+11

, . . , , . ( ) , .

, PDB ( ) - , . , , ( ). .

+3

, , , , .

,

if( this.SubObject == null )
{
    throw new Exception("Could not perform METHOD - SubObject is null.");
}
else
{
...
}

. ; , .

+2

, . null , ArgumentNullException.

, , , . , - , , null:

public void Method([NotNull] string name) { ...

...

name.CheckNotNull();
+2

If you're just looking for a more compact way of coding against null references, don't lose sight of the MSDN null coalescing operator??

Obviously, it depends on what you are doing, but it can be used to avoid additional if commands.

+2
source

All Articles