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

Type checking patterns in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Type checking patterns help you check what kind of data you have and use it safely in your code.

When you want to do something only if a variable is a certain type.
When you want to get a value from an object if it matches a type.
When you want to avoid errors by checking types before using data.
When you want to write clear and simple code that handles different data types.
Syntax
C Sharp (C#)
if (variable is TypeName name) {
    // use 'name' here
}

The is keyword checks the type and assigns the variable if it matches.

This pattern helps avoid extra casting and makes code safer and cleaner.

Examples
This checks if obj is a string, then uses it as s.
C Sharp (C#)
object obj = "hello";
if (obj is string s) {
    Console.WriteLine(s.ToUpper());
}
This checks if obj is an int, then adds 10 to it.
C Sharp (C#)
object obj = 123;
if (obj is int number) {
    Console.WriteLine(number + 10);
}
You can also check if an object is null using is null.
C Sharp (C#)
object obj = null;
if (obj is null) {
    Console.WriteLine("Object is null");
}
Sample Program

This program checks each item in an array. It prints the uppercase string if it's a string, adds 1 if it's an integer, notes if it's null, and says "Other type detected" for anything else.

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.ToUpper()}");
            } else if (item is int number) {
                Console.WriteLine($"Integer: {number + 1}");
            } else if (item is null) {
                Console.WriteLine("Null value found");
            } else {
                Console.WriteLine("Other type detected");
            }
        }
    }
}
OutputSuccess
Important Notes

Type checking patterns reduce the need for manual casting and make code safer.

They work well with switch statements for cleaner multi-type checks.

Summary

Type checking patterns let you test and use variables by their type easily.

They help avoid errors by ensuring you only use data in the right way.

Using is TypeName name is a simple and clear way to check types and get values.