Google News
logo
C# - Interview Questions
What is the difference between "is" and "as" operators in C#?
C# includes three keywords that support runtime type identification : is, as, and typeof
 
is operator : We can determine if an object is of a particular type by using the is operator. Its general form is shown here:
 
expr is type
 
Here, expr is an expression that describes an object whose type is being tested against type. If the type of expr is that the same as, or compatible with, type, then the result of this operation is true. Otherwise, it is false. Thus, if the result is true, expr is a  form of type. Because it applies to is, one type is compatible with another if both are the equivalent of type, or if a reference, boxing, or unboxing conversion exists.
 
As operator : Sometimes if we want to try a conversion at runtime, but not throw an exception if the conversion fails (which is the case when a cast is used). To do this, use the as operator, which has this general form:
 
expr as type
 
Here, expr is the expression being converted to type. If the conversion succeeds, then a reference to type is returned. Else, a null reference is returned. The as the operator can be used to perform only reference, boxing, unboxing, or identity conversions. The as operator offers a streamlined alternative to is in some cases.
Advertisement