Skip to main content
The as operator is a binary operator in C# used to perform safe explicit reference conversions, boxing conversions, and unboxing conversions (specifically to nullable value types). It evaluates an expression and attempts to cast it to a specified target type. If the conversion is successful, it returns the casted object; if the conversion fails, it returns null rather than throwing an InvalidCastException.

Semantic Equivalence

At runtime, the as operator is strictly a type-testing and casting mechanism. It is semantically equivalent to using the is operator followed by a direct cast, except the expression is evaluated only once.

Type Constraints

Because a failed conversion results in a null value, the as operator enforces strict constraints on the target type:
  1. Reference Types: The target type can be any class, interface, delegate, or array.
  2. Nullable Value Types: The target type can be a Nullable<T> (e.g., int?, DateTime?).
  3. Non-Nullable Value Types: The as operator cannot be used with non-nullable value types (e.g., int, bool, struct). Attempting to do so results in a compile-time error, as these types cannot hold a null value.

Conversion Rules

The as operator only considers specific types of conversions. It will successfully cast if the runtime type of the expression:
  • Is exactly the target type.
  • Derives from the target type (upcasting).
  • Implements the target interface.
  • Can be boxed to the target type.
  • Is the underlying non-nullable value type of the target Nullable<T> (e.g., unboxing a boxed int to int?).
Crucial Distinction: Unlike standard casting syntax (TargetType)expression, the as operator does not invoke user-defined conversions, implicit numeric conversions, or explicit numeric conversions.

Compile-Time Validation

The C# compiler performs static analysis on the as operator. If the compiler determines that a conversion is mathematically impossible based on the static types (e.g., attempting to cast a sealed class to an interface it does not implement), it will generate a compile-time error (CS0039) rather than deferring the failure to runtime.
Tired of Poor C# Skills? Fix That With Deep Grasping!Learn More