Created
December 4, 2012 14:04
-
-
Save driscollwebdev/4204221 to your computer and use it in GitHub Desktop.
Null + Type checking with cast (bad) and with is operator (good)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This is bad, don't do this: | |
if ((SubclassType)BaseClassInstance != null) | |
{ | |
//this will run, maybe, who knows? | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This is better, but still ugly... | |
try | |
{ | |
if ((SubclassType)BaseClassInstance != null) | |
{ | |
//this will run, maybe, who knows? | |
} | |
} | |
catch (InvalidCastException ex) | |
{ | |
//handle the error | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Do this instead: | |
if (BaseClassInstance is SubclassType) | |
{ | |
//ah, much better... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment