Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# is vs as: Type Checking and Safe Casting

C# is vs as: Understand the differences between C#'s is and as operators for type checking and safe casting, including syntax, runtime behavior, and when to use each.

~5 min readC#
#C# operators#type checking#type casting#pattern matching
A visual comparison of the C# is and as operators, showing type checking and safe casting with a diagram of an object being tested and converted.

When you need to check whether an object is of a certain type or convert it to that type, C# offers two operators: is and as. Both are used for type testing and conversion, but they behave differently and are suited to different scenarios. Understanding the difference is essential for writing type-safe code that handles runtime types correctly.

The is Operator for Type Checking

The is operator evaluates a type pattern and returns a boolean indicating whether the runtime type of an expression is compatible with a given type. The simplest form is:

csharp
object value = "hello"; if (value is string) { Console.WriteLine("value is a string"); }

Here, value is string returns true if the runtime type of value is string or a type derived from string (since string is sealed, that means exactly string). For reference types, is returns false when the expression is null and true only when the runtime type is compatible with the tested type. It does not throw exceptions.

Since C# 7.0, is supports pattern matching, allowing you to declare a variable in the same expression:

csharp
if (value is string text) { Console.WriteLine(text.Length); }

This combines a type test with a cast, assigning text only when the type matches. The variable text is in scope inside the if block and is definitely assigned. This pattern is more concise than a separate cast and null check.

The as Operator for Safe Casting

The as operator performs a safe cast that returns null instead of throwing an InvalidCastException when the conversion fails. It works only with reference types and nullable value types. For example:

csharp
object value = "hello"; string text = value as string; if (text != null) { Console.WriteLine(text.Length); }

If value is not a string or is null, text becomes null. The as operator does not work with non-nullable value types like int or double; attempting to use it that way is a compile-time error. To cast value types, you must use a regular cast or is with a pattern.

Key Differences Between is and as

OperatorReturnsThrows on failureWorks with value typesTypical use
isboolNoYes (with pattern)Type checking and pattern matching
asThe converted type or nullNoNo (only reference and nullable value types)Safe casting to a reference type

The most important difference is the return type. is gives you a boolean, so you can use it in conditionals without worrying about the actual converted value. as gives you the converted value or null, so you must check for null before using it. This makes as a direct replacement for the old pattern:

csharp
if (value is SomeType) { SomeType st = (SomeType)value; // ... }

which can be rewritten as:

csharp
SomeType st = value as SomeType; if (st != null) { // ... }

The is pattern approach is often more readable because it declares the variable inline.

Performance and Runtime Behavior

Both is and as are implemented as IL instructions (isinst for as, and isinst plus a branch for is in its simple form). In practice, the runtime cost is similar for simple type checks. However, pattern matching with is can introduce additional overhead if the pattern is complex, such as property patterns or recursive patterns. For simple type checks, the difference is negligible.

One subtle performance consideration is that using as followed by a null check avoids a double type check. With the old is + cast pattern, you perform two type checks: one in is and one in the cast. With as, you perform only one. The modern is pattern also performs only one check because it combines the test and the assignment.

For boxed value types, is with a type pattern avoids a second unboxing after the type check. For example:

csharp
object boxed = 42; if (boxed is int number) { // number is the int value, no separate cast needed }

The pattern performs the type test and extracts the value in one step. as is not available here for a non-nullable int, but you could use as int? if a nullable result is acceptable.

Common Mistakes and How to Avoid Them

A frequent mistake is using as with a non-nullable value type. The compiler rejects the code, but developers sometimes try to work around it by starting from a boxed value:

csharp
object boxed = 42; int? maybeInt = boxed as int?; // Valid: nullable value types are supported by `as`

The as operator supports Nullable<T>. If boxed is not a boxed int or is null, maybeInt is null. However, this is often less clear than using is:

csharp
if (boxed is int number) { // use number }

Another common point is null checking. value is null is valid and equivalent to value == null, and both forms are widely used. The important detail is that as treats a null source the same as a failed conversion, so the result is null. If you need to distinguish "the object was null" from "the object was of a different type", inspect the original object explicitly.

Choosing Between is and as

Use is when you need to:

  • Check if an object is of a specific type without needing the converted value.
  • Use pattern matching to extract the value in a single step.
  • Work with value types.

Use as when you need to:

  • Convert a reference type to a derived type and are comfortable handling null for failure.
  • Prefer a separate null check after the cast.
  • Need to maintain compatibility with older C# versions (pre-7.0) where is did not support patterns.

In modern C#, the is pattern is often the better choice because it combines the type test and the conversion, leading to clearer and more concise code. However, if you need to reuse the converted value in multiple places, as might be more convenient because you assign it once and check for null once.

Pattern Matching with is in Modern C#

C# 7.0 introduced type patterns, and later versions added property patterns, positional patterns, and relational patterns. These make is much more powerful than a simple type check. For example:

csharp
public static string Describe(object obj) { if (obj is Point p && p.X > 0 && p.Y > 0) { return "Point in first quadrant"; } else if (obj is string s && s.Length > 10) { return "Long string"; } return "Unknown"; }

Here, is is used not only for type checking but also for evaluating conditions on the extracted value. This capability goes far beyond what as can do. When you need complex type-based logic, is pattern matching is the idiomatic choice.

The as operator remains useful in scenarios where you want a simple, null-based conversion without pattern matching. For example, in a method that accepts object and returns a string representation, you might use:

csharp
string text = value as string; if (text != null) { return text.ToUpper(); }

This is straightforward and works in all C# versions.

In summary, is and as are not about which operator is "better" in absolute terms; it is about selecting the right tool for the specific type-checking and conversion scenario. The is operator with pattern matching offers more expressive power, while as provides a simple, null-based cast for reference types. Understanding their differences helps you write code that is both correct and maintainable.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.