Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

as: practical reference

as: practical reference: as attempts a reference, nullable, boxing, or unboxing conversion and returns null on failure.

Version: C# language; verified against C# 14 reference

Syntax

left as right

as attempts a reference, nullable, boxing, or unboxing conversion and returns null on failure.

Use it when type mismatch is expected and you immediately test the result for null.

It does not perform ordinary numeric conversions or target non-nullable value types.

A null input and an incompatible type both produce null, so they cannot be distinguished.

The complete program actually uses as; its exact expected stdout is 4.

Examples

using System;
using System.Linq;
using System.Threading.Tasks;

object value = "text"; Console.WriteLine((value as string)?.Length);

Result

4

The complete program actually uses `as`; its exact expected stdout is `4`.

Sources