Skip to content

Instantly share code, notes, and snippets.

@BanksySan
Created April 19, 2020 10:04
Show Gist options
  • Save BanksySan/f78c59b90e60323bd3197fb512ed6ae4 to your computer and use it in GitHub Desktop.
Save BanksySan/f78c59b90e60323bd3197fb512ed6ae4 to your computer and use it in GitHub Desktop.
C# Casting Examples
try
{
target = (TargetType) o;
}
catch (InvalidCastException)
{
// Handle exception
}
if (o is TargetType target)
{
// Use target
}
else
{
// o is not a TargetType
}
var target = o as TargetType; // Compile type exception here is type isn't nullable
if (o != null)
{
// Use target object
}
else
{
// o is not a TargetType
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment