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 null
s.
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
foo
is not astring
: throwsInvalidCastException
. - Otherwise assigns
foo
tobar
(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
foo
is not astring
: assignsnull
tobar
; doesn't throw. - Otherwise assigns
foo
tobar
(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
foo
is not astring
or isnull
: returnsfalse
. - Otherwise returns
true
.- Also in the second example above:
assigns
foo
to a new variablebar
.
- Also in the second example above:
assigns
- Use in
if
statements to combine the usage of theas
operator andnull
check. - Use in
switch
statements 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
as
operator on Microsoft Docsis
operator on Microsoft Docs- Type testing with pattern matching on Microsoft Docs