0
0
C Sharp (C#)programming~5 mins

Type patterns in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Type patterns help you check if a value is a certain type and use it right away. This makes your code simpler and clearer.

When you want to check if an object is a specific type before using it.
When you want to safely convert an object to a type and use it in one step.
When you want to write cleaner code instead of separate type checks and casts.
When handling different types in a switch statement or if-else blocks.
When you want to avoid errors from wrong type conversions.
Syntax
C Sharp (C#)
if (variable is TypeName variableName) {
    // use variableName here
}

The is keyword checks the type and creates a new variable if it matches.

This new variable is only available inside the if-block.

Examples
Check if obj is a string and use it as s inside the block.
C Sharp (C#)
object obj = "hello";
if (obj is string s) {
    Console.WriteLine(s.ToUpper());
}
Check if obj is an int and add 10 to it.
C Sharp (C#)
object obj = 123;
if (obj is int number) {
    Console.WriteLine(number + 10);
}
Use type patterns in a switch to handle different types.
C Sharp (C#)
object obj = 3.14;
switch (obj) {
    case double d:
        Console.WriteLine($"Double: {d}");
        break;
    case int i:
        Console.WriteLine($"Int: {i}");
        break;
    default:
        Console.WriteLine("Unknown type");
        break;
}
Sample Program

This program checks each item in an array and prints its type and value using type patterns.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        object[] items = { "apple", 42, 3.14, null };

        foreach (var item in items) {
            if (item is string text) {
                Console.WriteLine($"String: {text}");
            } else if (item is int number) {
                Console.WriteLine($"Integer: {number}");
            } else if (item is double dbl) {
                Console.WriteLine($"Double: {dbl}");
            } else {
                Console.WriteLine("Unknown or null");
            }
        }
    }
}
OutputSuccess
Important Notes

Type patterns combine type checking and casting in one step.

They help avoid errors from wrong casts and make code easier to read.

Summary

Type patterns check and use a value's type in one step.

They simplify code by removing separate casts.

Useful in if statements and switch cases.