C#: Cast expression vs as operator vs is operator

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 foo is not a string: throws InvalidCastException.
  • Otherwise assigns foo to bar (can be null).
  • 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 a string: assigns null to bar; doesn't throw.
  • Otherwise assigns foo to bar (can be null).
  • 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 a string or is null: returns false.
  • Otherwise returns true.
    • Also in the second example above: assigns foo to a new variable bar.
  • Use in if statements to combine the usage of the as operator and null 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

Footnotes

  1. See: English: assume vs presume ↩ī¸Ž