if (x != null && x is String)
{
// stuff
}
[.net] C# - Check for null before is?
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:
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?
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.
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).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement