Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Why reflection is needed in C Sharp (C#) - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why reflection is needed
Start Program
↓
Need to inspect type info?
Yes↓
Use Reflection API
↓
Get type metadata
↓
Access properties, methods dynamically
↓
Perform actions based on metadata
↓
End Program
Reflection lets a program look at its own types and members while running, so it can decide what to do dynamically.
Execution Sample
C Sharp (C#)
Type type = typeof(string);
Console.WriteLine(type.Name);
var methods = type.GetMethods();
Console.WriteLine(methods.Length);
This code uses reflection to get the type info of string and prints its name and number of methods.
Execution Table
StepActionEvaluationResult
1Get type of stringtypeof(string)System.String type object
2Print type nametype.Name"String"
3Get all methodstype.GetMethods()Array of MethodInfo objects
4Print number of methodsmethods.LengthNumber of methods (e.g., 70)
5End--
💡 All reflection calls completed, program ends.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
typenullSystem.String type objectSystem.String type objectSystem.String type object
methodsnullnullArray of MethodInfo objectsArray of MethodInfo objects
Key Moments - 2 Insights
Why do we need to get the type object first?
Reflection works by inspecting a Type object; without it, we cannot access metadata. See step 1 in execution_table.
Why does methods.Length show many methods?
The string type has many inherited and declared methods. Reflection shows all available methods, not just those we wrote. See step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of type.Name at step 2?
A"System.String"
B"string"
C"String"
D"Type"
💡 Hint
Check the 'Evaluation' and 'Result' columns at step 2 in execution_table.
At which step do we get the array of methods?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for 'Get all methods' action in execution_table.
If we skip getting the type object, what happens to methods variable?
AIt becomes null because no type to inspect
BIt contains all methods anyway
CIt throws an error at runtime
DIt contains only one method
💡 Hint
See variable_tracker and key_moments about the importance of type object.
Concept Snapshot
Reflection lets C# programs inspect types and members at runtime.
Use typeof(TypeName) to get type info.
Access properties, methods dynamically via reflection APIs.
Useful for dynamic behavior, plugins, serialization.
Without reflection, code must know types at compile time.
Full Transcript
Reflection in C# allows a program to look at its own types and members while running. This is done by first getting a Type object using typeof(TypeName). Then, reflection methods like GetMethods() let the program see all methods of that type. This helps when the program needs to work with types it did not know about when it was written. For example, it can load plugins or serialize objects dynamically. The execution trace shows getting the string type, printing its name, getting all its methods, and printing how many methods it has. Variables like 'type' and 'methods' hold the reflection data. Reflection is needed because without it, the program cannot inspect or use types dynamically at runtime.

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

  1. Step 1: Understand what reflection does

    Reflection allows a program to look at its own structure, like classes and methods, while it is running.
  2. Step 2: Identify the purpose of reflection

    It is used to examine and interact with types dynamically, not for speed or UI creation.
  3. Final Answer:

    To examine and use information about types at runtime -> Option C
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Type t = obj.GetType(); -> Option A
  4. 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

  1. Step 1: Understand typeof operator

    typeof(string) returns the Type object for the string class.
  2. Step 2: Check what type.Name returns

    The Name property returns the class name without namespace, which is "String" with capital S.
  3. Final Answer:

    String -> Option B
  4. 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

  1. Step 1: Check method retrieval

    int (System.Int32) has a static method "Parse", so GetMethod("Parse") works.
  2. 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(...).
  3. Final Answer:

    Invoke returns object, needs casting to int -> Option A
  4. 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

  1. Step 1: Understand dynamic plugin loading

    When class name is unknown, you must load assembly dynamically and inspect types.
  2. 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.
  3. Final Answer:

    Use Assembly.Load, then find type with GetTypes(), then invoke Run method -> Option D
  4. Quick Check:

    Dynamic loading needs Assembly.Load + reflection [OK]
Hint: Load assembly, find type, invoke method dynamically [OK]
Common Mistakes:
  • Using typeof() without knowing class name
  • Trying to instantiate class by string name directly
  • Calling method without loading assembly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard