0
0
CsharpConceptBeginner · 3 min read

What is is keyword in C#: Usage and Examples

In C#, the is keyword checks if an object is compatible with a given type and returns true or false. It helps you safely test an object's type before using it.
⚙️

How It Works

The is keyword in C# acts like a type-checking tool. Imagine you have a box and you want to know if it contains a toy car or a doll. Instead of opening the box and guessing, you ask, "Is this a toy car?" The is keyword does the same for objects and types in your code.

When you write obj is Type, C# checks if the object obj can be treated as the specified Type. If yes, it returns true; otherwise, it returns false. This helps avoid errors when you try to use an object as a type it doesn't belong to.

💻

Example

This example shows how to use is to check an object's type before using it.

csharp
object obj = "Hello, world!";

if (obj is string)
{
    string message = (string)obj;
    System.Console.WriteLine($"The object is a string: {message}");
}
else
{
    System.Console.WriteLine("The object is not a string.");
}
Output
The object is a string: Hello, world!
🎯

When to Use

Use the is keyword when you need to confirm an object's type before working with it. This is especially useful when dealing with variables of type object or interfaces, where the actual type might vary.

For example, when you receive data from different sources or work with collections of mixed types, is helps you safely handle each item according to its real type. It prevents runtime errors caused by invalid type casts.

Key Points

  • is checks if an object is a specific type and returns a boolean.
  • It helps avoid errors by verifying type compatibility before casting.
  • Commonly used with object or interface types.
  • Introduced in early versions of C# and improved with pattern matching in newer versions.

Key Takeaways

The is keyword checks if an object is compatible with a given type and returns true or false.
Use is to safely test an object's type before casting to avoid runtime errors.
It is especially helpful when working with variables of type object or interfaces.
Modern C# versions support pattern matching with is for cleaner code.