Skip to content

is, as, and Cast Expressions

Question

Describe the differences between is, as, and a cast expression.

Short interview answer

is tests type compatibility and can capture a typed variable. as attempts a reference or nullable conversion and returns null if it fails. A cast expression performs an explicit conversion and can throw if a runtime reference conversion fails.

Detailed answer

Prefer pattern matching such as if (value is Customer customer) when testing and using a value. Use as only when a null result is the desired failure signal. Use an explicit cast when failure should be exceptional or a non-reference explicit conversion is required, while remembering that a failing reference cast can throw InvalidCastException.

Sources