What is the difference between the 'is' and 'as' operators?

C# Language Features Basic Fresher1–2 Yrs Conceptual 1 min read

Quick Answer

is returns a bool for a type test, and with a pattern it also binds a variable: if (o is string s). as attempts a reference/nullable conversion and returns null on failure instead of throwing: var s = o as string;. A direct cast (string)o throws InvalidCastException if it fails.

is is a boolean type test, and since C# 7 it can declare a variable at the same time — if (o is Foo f) tests and gives me f in one go. as does a cast that yields null rather than throwing if the type doesn't match, so it's for when “not this type” is a case you want to handle rather than an error. A plain cast throws. These days I almost always use the is pattern form; the old “as then check for null” and especially “is then cast” are both obsolete.

  • Use is with a pattern for “test and use” — it's the modern replacement for as-then-null-check.
  • Use as only when null is a meaningful “not that type” result you'll handle.
  • as can't be used with non-nullable value types (o as int won't compile; o as int? will).
  • Anti-pattern: if (o is Foo) { var f = (Foo)o; } — double type check; use the pattern form.