0
0
CsharpConceptBeginner · 3 min read

Type Pattern in C#: What It Is and How to Use It

In C#, a type pattern is a way to check if an object is a specific type and, if so, to extract it into a variable in one step. It is used with the is keyword to simplify type checking and casting in a clear and concise way.
⚙️

How It Works

Think of the type pattern as a smart way to ask, "Is this thing a certain kind of object?" and if yes, "Let me use it right away." Instead of first checking the type and then separately converting it, the type pattern does both in one simple step.

Imagine you have a box and you want to know if it contains a toy car. With a type pattern, you ask, "Is this box holding a toy car?" If yes, you get the toy car out and can play with it immediately. This saves you from opening the box twice.

In C#, this is done using the is keyword followed by the type and a variable name. If the object matches the type, the variable holds the casted object inside the if block or expression.

💻

Example

This example shows how to use a type pattern to check if an object is a string and then print its length.

csharp
object obj = "Hello, world!";

if (obj is string s)
{
    Console.WriteLine($"The string length is {s.Length}.");
}
else
{
    Console.WriteLine("The object is not a string.");
}
Output
The string length is 13.
🎯

When to Use

Use type patterns when you want to safely check an object's type and use it immediately without extra casting. This is common when working with variables of type object or interfaces where the exact type is not known upfront.

For example, when processing a list of different shapes, you can use type patterns to handle each shape type differently without writing verbose code. It makes your code cleaner, easier to read, and less error-prone.

Key Points

  • Type pattern combines type checking and casting in one step.
  • It uses the is keyword followed by a type and a variable name.
  • It improves code readability and safety by avoiding explicit casts.
  • Introduced in C# 7.0 and widely used in modern C# code.

Key Takeaways

Type pattern lets you check and cast an object in one simple step using 'is'.
It makes your code cleaner and safer by avoiding separate casts.
Use it when you need to work with objects of unknown or multiple types.
Type patterns were introduced in C# 7.0 and are a modern best practice.