Type checking and conversion are essential operations in C#'s object-oriented programming model.
The is and as keywords provide elegant solutions for safely working with types at runtime. Understanding when and how to use each can significantly improve your code's robustness and readability.
The is Operator: Type Checking
The is operator evaluates whether an object is compatible with a given type, returning a boolean result.
Basic Usage
object value = "Hello, World!";
// Check if value is a string
if (value is string)
{
Console.WriteLine("value is a string");
}
Pattern Matching (C# 7.0+)
// Type checking with declaration
if (value is string message)
{
// message is now a string variable containing the value
Console.WriteLine($"Length: {message.Length}");
}
Type Patterns with Conditions (C# 9.0+)
// Check type and condition in one step
if (value is string { Length: > 5 } longString)
{
Console.WriteLine($"Long string found: {longString}");
}
The as Operator: Safe Casting
The as operator attempts to cast an object to a specified reference type, returning null if the cast fails rather than throwing an exception.
Basic Usage
object value = "Hello, World!";
// Try to cast to string
string message = value as string;
// Check if cast was successful
if (message != null)
{
Console.WriteLine($"Successful cast: {message}");
}
Important Limitations
- The
as operator only works with reference types and nullable value types
- It cannot be used with non-nullable value types (use
is with pattern matching instead)
Choosing Between is and as
| Scenario |
Recommended Approach |
| Just checking type |
Use is |
| Checking type and using the object |
Use is with pattern matching |
| Possibly working with a null result |
Use as |
| Working with value types |
Use is (with pattern matching if needed) |
| Multiple operations on same cast |
Use as once, then check for null |
Best Practices
- Prefer pattern matching with
is when you need both type checking and casting
- Use
as when working with hierarchies where null is a valid outcome
- Avoid
as followed by null checking when is pattern matching works
- Remember that
as never throws exceptions, while direct casting can
- Consider extension methods as an alternative to frequent type checking
Understanding these operators helps you write more elegant, safe code when working with polymorphic types in C#.
Walt is a computer scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on: