📖 Scenario: Imagine you are building a tool that needs to work with different types of objects without knowing their details in advance. Reflection helps you look inside these objects while the program is running.
🎯 Goal: Learn how to use reflection in C# to inspect an object's type and properties at runtime.
📋 What You'll Learn
Create a simple class with some properties
Create an instance of the class
Use reflection to get the type name and property names
Print the type and property names to the console
💡 Why This Matters
🌍 Real World
Reflection is used in tools like serializers, debuggers, and frameworks that need to work with unknown types.
💼 Career
Understanding reflection helps you build flexible and powerful C# applications, a valuable skill in many software development jobs.
Progress0 / 4 steps
1
Create a class called Person with properties Name and Age
Write a class called Person with two public properties: Name of type string and Age of type int.
C Sharp (C#)
Hint
Use public class Person and add public string Name { get; set; } and public int Age { get; set; }.
2
Create an instance of Person called person with Name = "Alice" and Age = 30
Create a variable called person and set it to a new Person object with Name set to "Alice" and Age set to 30.
C Sharp (C#)
Hint
Use Person person = new Person { Name = "Alice", Age = 30 }; to create the object.
3
Use reflection to get the type name and property names of person
Use Type personType = person.GetType() to get the type. Then use personType.Name to get the type name. Use personType.GetProperties() to get the properties.
C Sharp (C#)
Hint
Use person.GetType() and GetProperties() methods to inspect the object.
4
Print the type name and property names of person
Print the type name using Console.WriteLine(personType.Name). Then use a foreach loop with PropertyInfo property in properties to print each property name using Console.WriteLine(property.Name).
C Sharp (C#)
Hint
Use Console.WriteLine to print the type and property names.
Practice
(1/5)
1. Why do programmers use reflection in C#?
easy
A. To manage memory manually
B. To write faster code by avoiding loops
C. To examine and use information about types at runtime
D. To create graphical user interfaces
Solution
Step 1: Understand what reflection does
Reflection allows a program to look at its own structure, like classes and methods, while it is running.
Step 2: Identify the purpose of reflection
It is used to examine and interact with types dynamically, not for speed or UI creation.
Final Answer:
To examine and use information about types at runtime -> Option C
Quick Check:
Reflection = runtime type info [OK]
Hint: Reflection inspects types during program run [OK]
Common Mistakes:
Confusing reflection with UI design
Thinking reflection speeds up code
Believing reflection manages memory
2. Which of the following is the correct way to get the type of an object obj using reflection in C#?
easy
A. Type t = obj.GetType();
B. Type t = GetType(obj);
C. Type t = typeof(obj);
D. Type t = obj.Type();
Solution
Step 1: Recall the method to get an object's type
In C#, the method GetType() is called on the object instance to get its type.
Step 2: Check each option's syntax
Type t = obj.GetType(); uses obj.GetType(), which is correct. Type t = GetType(obj); and D are invalid syntax. Type t = typeof(obj); uses typeof incorrectly because it expects a type name, not an object.
Final Answer:
Type t = obj.GetType(); -> Option A
Quick Check:
obj.GetType() gets type [OK]
Hint: Use obj.GetType() to get runtime type [OK]
Common Mistakes:
Using typeof with an object instance
Calling non-existent methods like obj.Type()
Trying to pass object to GetType as argument
3. What will be the output of this C# code?
using System;
class Program {
static void Main() {
var type = typeof(string);
Console.WriteLine(type.Name);
}
}
medium
A. string
B. String
C. System.String
D. Type
Solution
Step 1: Understand typeof operator
typeof(string) returns the Type object for the string class.
Step 2: Check what type.Name returns
The Name property returns the class name without namespace, which is "String" with capital S.
Final Answer:
String -> Option B
Quick Check:
typeof(string).Name = "String" [OK]
Hint: typeof(T).Name returns class name without namespace [OK]
Common Mistakes:
Confusing lowercase 'string' keyword with class name
Expecting full namespace in Name property
Thinking output is 'Type'
4. Identify the error in this reflection code snippet:
Type t = typeof(int);
var method = t.GetMethod("Parse");
int result = method.Invoke(null, new object[] { "123" });
Console.WriteLine(result);
medium
A. Invoke returns object, needs casting to int
B. GetMethod("Parse") does not exist on int
C. typeof(int) should be typeof(Int32)
D. Invoke cannot be called with null as first argument
Solution
Step 1: Check method retrieval
int (System.Int32) has a static method "Parse", so GetMethod("Parse") works.
Step 2: Check Invoke return type and usage
Invoke returns an object. Assigning it directly to int causes a compile error. It needs explicit cast: (int)method.Invoke(...).
Final Answer:
Invoke returns object, needs casting to int -> Option A
Quick Check:
Invoke returns object, cast needed [OK]
Hint: Cast Invoke result to correct type [OK]
Common Mistakes:
Ignoring cast from object to int
Thinking GetMethod("Parse") is invalid
Assuming typeof(int) is wrong
5. You want to load a plugin assembly at runtime and call its method Run without knowing the class name beforehand. Which reflection approach is best?
hard
A. Call Run method without loading assembly
B. Use typeof() with class name, then call Run directly
C. Use new operator with class name string
D. Use Assembly.Load, then find type with GetTypes(), then invoke Run method
Solution
Step 1: Understand dynamic plugin loading
When class name is unknown, you must load assembly dynamically and inspect types.
Step 2: Use reflection to find and invoke method
Assembly.Load loads the plugin. GetTypes() lists classes. Then you find the class with Run method and invoke it.
Final Answer:
Use Assembly.Load, then find type with GetTypes(), then invoke Run method -> Option D