[.net] C# - Check for null before is?

Started by
5 comments, last by Promit 15 years, 1 month ago
Quick question. Is there a reason (perhaps for performance) to check if a variable is null before checking if it "is" a type? For example:

if (x != null && x is String)
{
// stuff
}

I know that would compile and run just fine without the check for null, even if x is, indeed, null. Is the (x != null) completely redundant?
Without order nothing can exist - without chaos nothing can evolve.
Advertisement
I would assume that it's redundant. The first thing 'is' would need to do is get the type of x, and this would involve a null check.
MSDN is your friend: http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx

Quote:An is expression evaluates to true if both of the following conditions are met:

expression is not null.
expression can be cast to type. That is, a cast expression of the form (type)(expression) will complete without throwing an exception. For more information, see 7.6.6 Cast expressions.
A compile-time warning will be issued if the expression expression is type is known to always be true or always be false.
I thought as much. Thanks!
Without order nothing can exist - without chaos nothing can evolve.
Quote:Original post by CyberSlag5k
Quick question. Is there a reason (perhaps for performance) to check if a variable is null before checking if it "is" a type? For example:

*** Source Snippet Removed ***

I know that would compile and run just fine without the check for null, even if x is, indeed, null. Is the (x != null) completely redundant?

When I run into something like this I often do this:
SomeType myObject = x as SomeType;if (x != null){   Process(x);}

The key here is the 'as'. If the object is not the type that we're trying to convert to, it'll return NULL.

According to FXCop this performs better than using 'is' and then casting to the type (which I assume you'll be doing since you're concerned with the type up front).
Makes sense. Thanks.
Without order nothing can exist - without chaos nothing can evolve.
I do that as well, but examples on MSDN invariably use is and a cast. Weird.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.

This topic is closed to new replies.

Advertisement