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

Getting type information at runtime in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Getting type information at runtime
📖 Scenario: Imagine you are building a simple program that needs to check what kind of objects it is working with while running. This is like checking the label on a box before opening it to know what's inside.
🎯 Goal: You will create a program that stores different objects, then finds out and prints their types while the program is running.
📋 What You'll Learn
Create a list called items with different types of objects
Create a variable called count to store the number of items
Use a for loop with variable i to go through items
Inside the loop, get the type of each item using GetType()
Print the type name of each item using Console.WriteLine
💡 Why This Matters
🌍 Real World
Programs often need to check what kind of data they are working with to decide what to do next. For example, a program that reads files might check if the content is text or numbers.
💼 Career
Understanding how to get type information at runtime helps in debugging, logging, and writing flexible code that can handle different data types safely.
Progress0 / 4 steps
1
Create a list of different objects
Create a list called items that contains these exact objects: 42 (an integer), "hello" (a string), and 3.14 (a double).
C Sharp (C#)
Need a hint?

Use List<object> to hold different types together.

2
Create a variable to count the items
Create an integer variable called count and set it to the number of items in the items list using items.Count.
C Sharp (C#)
Need a hint?

Use int count = items.Count; to get the number of items.

3
Loop through the list and get each item's type
Use a for loop with variable i from 0 to count - 1 to go through the items list. Inside the loop, create a variable called itemType and set it to the type of the current item using items[i].GetType().
C Sharp (C#)
Need a hint?

Use for (int i = 0; i < count; i++) and items[i].GetType().

4
Print the type name of each item
Inside the for loop, add a line to print the type name of each item using Console.WriteLine(itemType.Name).
C Sharp (C#)
Need a hint?

Use Console.WriteLine(itemType.Name); to print the type name.