Casting in C#: cast expression vs as and is operators
Published on in C# and Mnemonics
Last updated on
A cast expression like (string)foo throws
if the types don't match.
The as operator doesn't throw
and defaults to null.
The is operator doesn't throw
and ignores nulls.
Table of contents
Cast expression
Sometimes called "direct casting."
try {
var bar = (string)foo;
// `bar` is a `string` (can be `null`)
} catch (InvalidCastException) {
// `foo` is not a `string`
}
- If
foois not astring: throwsInvalidCastException. - Otherwise assigns
footobar(can benull). - Use when you are sure that the type is correct.
as operator
var bar = foo as string;
if (bar != null) {
// `bar` is a `string` and not `null`
}
- If
foois not astring: assignsnulltobar; doesn't throw. - Otherwise assigns
footobar(can benull). - Use when the type might be correct.
is operator
if (foo is string) {
// `foo` is a `string` and not `null`
}
if (foo is string bar) {
// `bar` is a `string` and not `null`
}
- If
foois not astringor isnull: returnsfalse. - Otherwise returns
true.- Also in the second example above:
assigns
footo a new variablebar.
- Also in the second example above:
assigns
- Use in
ifstatements to combine the usage of theasoperator andnullcheck. - Use in
switchstatements for type pattern matching.
Mnemonic: cast expression vs as operator
Use the as operator
when you only as-sume[1] that the type is correct.
If your assumption is incorrect,
that's okay!
You'll get a null
and no exception will be thrown.
Conversely, if you are sure that the type is correct, use a cast ex-pression. You'll be punished with an ex-ception if you are wrong.
Sources / Further resources
- Direct casting vs 'as' operator? on Stack Overflow
- Cast expression on Microsoft Docs
asoperator on Microsoft Docsisoperator on Microsoft Docs- Type testing with pattern matching on Microsoft Docs