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

Getting type information at runtime in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Sometimes, you want to know what kind of thing (type) a variable or object is while the program is running. This helps you make decisions or handle data correctly.

When you want to check if an object is a certain type before using it.
When you need to print or log the type of an object for debugging.
When writing code that works with different types and needs to behave differently.
When you want to get the name of a type to display to users or save in files.
Syntax
C Sharp (C#)
Type typeInfo = obj.GetType();
string typeName = obj.GetType().Name;

GetType() is a method that tells you the exact type of an object.

You can get the full type info or just the name using Name property.

Examples
This prints the full type of number, which is System.Int32.
C Sharp (C#)
int number = 5;
Type typeInfo = number.GetType();
Console.WriteLine(typeInfo);
This prints just the name of the type, which is String.
C Sharp (C#)
string text = "hello";
Console.WriteLine(text.GetType().Name);
This checks if obj is a double and prints a message.
C Sharp (C#)
object obj = 3.14;
if (obj.GetType() == typeof(double))
{
    Console.WriteLine("It's a double!");
}
Sample Program

This program loops through different items, gets their type at runtime, and prints both the value and its type name.

C Sharp (C#)
using System;

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

        foreach (var item in items)
        {
            Type type = item.GetType();
            Console.WriteLine($"Value: {item}, Type: {type.Name}");
        }
    }
}
OutputSuccess
Important Notes

Using GetType() works only on objects, so value types like int are boxed when used this way.

You can compare types using == and typeof() to check for specific types.

Summary

GetType() tells you the exact type of an object while the program runs.

You can use the type info to make decisions or show type names.

Comparing types helps you handle different data safely.