What is the difference between the is and as operators?

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

Quick Answer

is tests whether an object is compatible with a type and returns bool (and can declare a variable: if (o is Customer c)). as performs a cast that returns null instead of throwing if it fails — only for reference types and nullable value types. A direct cast (Customer)o throws InvalidCastException on failure.

is checks compatibility and gives me a bool — and with the pattern form, o is Customer c, it also gives me the typed variable if it matches. as is a cast that returns null on failure instead of throwing, so it's for reference types and I have to null-check afterwards. A plain cast throws InvalidCastException. These days I almost always use the is pattern because it does the check and the assignment together, so there's only one type check.

  • if (o is Customer) — check only. Modern: if (o is Customer c) — check + assign in one step (preferred).
  • var c = o as Customer; — c is null if o isn't a Customer. You then null-check c.
  • Anti-pattern: if (o is Customer) { var c = (Customer)o; } — two type checks. Use the is pattern.
  • as can't be used with value types like int (use o is int i).