Created
April 19, 2020 10:04
-
-
Save BanksySan/f78c59b90e60323bd3197fb512ed6ae4 to your computer and use it in GitHub Desktop.
C# Casting Examples
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
try | |
{ | |
target = (TargetType) o; | |
} | |
catch (InvalidCastException) | |
{ | |
// Handle exception | |
} |
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
if (o is TargetType target) | |
{ | |
// Use target | |
} | |
else | |
{ | |
// o is not a TargetType | |
} |
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
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