What is the difference between the is and as operators?
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;—cisnullifoisn't aCustomer. You then null-checkc.- Anti-pattern:
if (o is Customer) { var c = (Customer)o; }— two type checks. Use theispattern. ascan't be used with value types likeint(useo is int i).