DEV Community

Mrunal Meshram
Mrunal Meshram

Posted on

Understanding the `as` and `is` Keywords in C#

When working with type conversions and runtime type checking in C#, two small yet powerful keywords — as and is — often come into play. While they seem similar at first glance, they serve distinct purposes. Knowing when and how to use them effectively can make your code cleaner, safer, and more efficient.


🧩 The is Keyword — Type Checking Made Simple

The is keyword is used to check whether an object is compatible with a given type at runtime. It returns a boolean (true or false) based on whether the object can be safely cast to that type.

Syntax:

if (obj is MyClass)
{
    // obj can be safely cast to MyClass
}
Enter fullscreen mode Exit fullscreen mode

Example:

object value = "Hello World";

if (value is string)
{
    Console.WriteLine("It's a string!");
}
Enter fullscreen mode Exit fullscreen mode

Output:

It's a string!
Enter fullscreen mode Exit fullscreen mode

Modern Pattern Matching

Since C# 7.0, is also supports pattern matching, allowing you to both check and cast in one line:

if (value is string text)
{
    Console.WriteLine($"String length: {text.Length}");
}
Enter fullscreen mode Exit fullscreen mode

No need for an explicit cast — the compiler automatically assigns the value to a new variable of the target type.


🔄 The as Keyword — Safe Type Casting

The as keyword is used to perform type conversion between compatible reference types (or nullable types). If the conversion fails, it doesn’t throw an exception — instead, it returns null.

Syntax:

MyClass obj = someObject as MyClass;
Enter fullscreen mode Exit fullscreen mode

Example:

object data = "C# Keyword Demo";

string text = data as string;

if (text != null)
{
    Console.WriteLine($"String value: {text}");
}
Enter fullscreen mode Exit fullscreen mode

Output:

String value: C# Keyword Demo
Enter fullscreen mode Exit fullscreen mode

If data wasn’t a string, text would simply be null instead of causing an InvalidCastException.


⚖️ is vs as — The Key Difference

Feature is Keyword as Keyword
Purpose Type checking Type casting
Return Type bool Target type or null
Throws Exception on Failure No No
Usage Context Conditional checks Assignments
Best Use Case When you only need to know if the type matches When you want to safely cast and use the object

🚀 Best Practices

  • Use is with pattern matching to simplify your type checks and avoid redundant casts.
  • Use as when you want a safe cast without risking exceptions.
  • Avoid unnecessary type checks if polymorphism or interfaces can solve the problem more cleanly.

🧠 Quick Summary

Both as and is keywords provide safer and more readable ways to handle types in C#.

  • Use is to verify a type.
  • Use as to convert safely to a type.

Mastering these small details can significantly improve your code’s reliability and readability.

Top comments (0)