Skip to content

Instantly share code, notes, and snippets.

@driscollwebdev
Created December 4, 2012 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save driscollwebdev/4204224 to your computer and use it in GitHub Desktop.
Save driscollwebdev/4204224 to your computer and use it in GitHub Desktop.
Null + Type checking with cast (bad) and with is operator (good)
//This is bad, don't do this:
if ((SubclassType)BaseClassInstance != null)
{
//this will run, maybe, who knows?
}
//This is better, but still ugly...
try
{
if ((SubclassType)BaseClassInstance != null)
{
//this will run, maybe, who knows?
}
}
catch (InvalidCastException ex)
{
//handle the error
}
//Do this instead:
if (BaseClassInstance is SubclassType)
{
//ah, much better...
}
//Not sure which is uglier...
if(BaseClassInstance != null && BaseClassInstance.GetType() == typeof(SubclassType))
{
//wow, that was a mouthful.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment