What if your code could instantly know what kind of thing it's dealing with, just like you recognize your favorite toy at a glance?
Why Type patterns in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a box full of different toys, and you want to pick out only the cars. Without a clear way to check each toy's type, you have to open the box, look at each toy carefully, and guess if it's a car or not.
Manually checking each toy's type is slow and tiring. You might make mistakes, like confusing a truck for a car. If you add more toy types, the guessing game becomes even more confusing and error-prone.
Type patterns let you quickly and clearly check what kind of toy you have. You can write simple rules that say, "If this is a car, do this," making your code easier to read and less likely to make mistakes.
if (obj is Car) { var car = (Car)obj; /* use car */ } else if (obj is Truck) { var truck = (Truck)obj; /* use truck */ }
if (obj is Car car) { /* use car */ } else if (obj is Truck truck) { /* use truck */ }
Type patterns make your code smarter and cleaner by letting it recognize and handle different types easily and safely.
Think of a cashier scanning items: type patterns help the system quickly identify if an item is fruit, a drink, or a snack, so it can apply the right price and discount automatically.
Manual type checks are slow and error-prone.
Type patterns simplify and clarify type checking.
They make code safer and easier to maintain.