What is the difference between the 'is' and 'as' operators?
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
iswith a pattern for “test and use” — it's the modern replacement foras-then-null-check. - Use
asonly whennullis a meaningful “not that type” result you'll handle. ascan't be used with non-nullable value types (o as intwon't compile;o as int?will).- Anti-pattern:
if (o is Foo) { var f = (Foo)o; }— double type check; use the pattern form.