Is vs As in C#: Key Differences and When to Use Each
is checks if an object is a certain type and returns a boolean, while as tries to cast an object to a type and returns null if it fails. Use is for type checking and as for safe casting without exceptions.Quick Comparison
Here is a quick side-by-side comparison of is and as operators in C#.
| Feature | is | as |
|---|---|---|
| Purpose | Checks if an object is a specific type | Attempts to cast an object to a type |
| Return Type | Boolean (true/false) | Object of target type or null |
| Failure Behavior | Returns false | Returns null (no exception) |
| Use Case | Type checking before casting | Safe casting without exceptions |
| Works With Nullable Types | Yes | Yes |
| Throws Exception on Failure | No | No |
Key Differences
The is operator in C# is used to check if an object is compatible with a given type. It returns true if the object can be cast to that type, otherwise false. This is useful when you want to verify the type before performing operations.
The as operator attempts to cast an object to a specified type. If the cast is not possible, it returns null instead of throwing an exception. This makes as safer for casting when you expect that the cast might fail.
Unlike a direct cast, which throws an exception on failure, as lets you handle the failure gracefully by checking for null. However, as only works with reference types and nullable types, not with value types directly.
Code Comparison
Using is to check type before casting:
object obj = "hello"; if (obj is string s) { System.Console.WriteLine($"String length: {s.Length}"); } else { System.Console.WriteLine("Not a string"); }
<code>as</code> Equivalent
Using as to safely cast and check for null:
object obj = "hello"; string s = obj as string; if (s != null) { System.Console.WriteLine($"String length: {s.Length}"); } else { System.Console.WriteLine("Not a string"); }
When to Use Which
Choose is when you only need to check if an object is a certain type, especially before casting or branching logic. It is clear and straightforward for type checks.
Choose as when you want to cast an object safely without risking an exception, and you plan to check for null to handle failure. This is ideal for reference types and nullable types.
Key Takeaways
is checks type and returns a boolean, use it for type verification.as attempts safe casting and returns null on failure, use it to avoid exceptions.as works only with reference and nullable types, not value types.is when you only need to know the type, use as when you want the casted object.