How reflection bypasses compile-time safety in C Sharp (C#) - Performance & Efficiency
We want to understand how using reflection affects the time it takes for a program to run.
Specifically, how does reflection change the cost compared to normal code checked at compile time?
Analyze the time complexity of the following code snippet.
using System;
using System.Reflection;
class Program {
static void Main() {
Type t = typeof(string);
MethodInfo[] methods = t.GetMethods();
foreach (var method in methods) {
Console.WriteLine(method.Name);
}
}
}
This code uses reflection to get all methods of the string type and prints their names.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all methods returned by reflection.
- How many times: Once for each method in the string type, which depends on the number of methods defined.
As the number of methods in the type grows, the time to retrieve and loop through them grows roughly in direct proportion.
| Input Size (number of methods) | Approx. Operations |
|---|---|
| 10 | About 10 operations to process methods |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The work grows linearly with the number of methods found by reflection.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of methods increases.
[X] Wrong: "Reflection runs as fast as normal method calls because it just looks up methods."
[OK] Correct: Reflection does extra work at runtime to find and inspect methods, so it is slower and its cost grows with the number of members it processes.
Understanding how reflection affects performance helps you explain trade-offs when using dynamic features in real projects.
"What if we cached the MethodInfo array instead of calling GetMethods() every time? How would the time complexity change?"
Practice
Solution
Step 1: Understand reflection capabilities and identify how compile-time safety is bypassed
Reflection allows a program to look at its own structure and change it while running, which is not checked at compile time. Because reflection works at runtime, it can access private members and change types without compile-time type checking.Final Answer:
Inspect and modify types and members at runtime, ignoring compile-time checks -> Option CQuick Check:
Reflection bypasses compile-time safety = D [OK]
- Thinking reflection improves compile-time safety
- Confusing reflection with compile-time code generation
- Assuming reflection prevents runtime errors
_secret from a class MyClass?Solution
Step 1: Identify correct reflection method for fields and use correct BindingFlags for private instance fields
To get a field, use GetField, not GetProperty or GetMethod. Private fields require BindingFlags.NonPublic and BindingFlags.Instance to be accessed.Final Answer:
var field = typeof(MyClass).GetField("_secret", BindingFlags.NonPublic | BindingFlags.Instance); -> Option DQuick Check:
Correct BindingFlags for private field = A [OK]
- Omitting BindingFlags causing null result
- Using GetProperty instead of GetField
- Using BindingFlags.Public for private members
class Person { private int age = 30; }
var p = new Person();
var field = typeof(Person).GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(p, 40);
Console.WriteLine(field.GetValue(p));
What will be the output when this code runs?Solution
Step 1: Understand reflection access to private field and trace the value change and output
The code uses reflection with correct BindingFlags to access and modify the private fieldage. The field value is set to 40, then retrieved and printed, so output is 40.Final Answer:
40 -> Option AQuick Check:
Reflection sets private field value = 40 [OK]
- Assuming private fields cannot be changed
- Expecting compile-time error
- Thinking output remains original value
Calculate in class Calculator. What is the error and how to fix it?
var calc = new Calculator();
var method = typeof(Calculator).GetMethod("Calculate");
method.Invoke(calc, null);Solution
Step 1: Identify why GetMethod returns null and fix by adding correct BindingFlags
By default, GetMethod only finds public methods. Private methods require BindingFlags.NonPublic and BindingFlags.Instance. Use GetMethod("Calculate", BindingFlags.NonPublic | BindingFlags.Instance) to find the private method.Final Answer:
GetMethod returns null because it needs BindingFlags.NonPublic; fix by adding BindingFlags.NonPublic | BindingFlags.Instance -> Option AQuick Check:
Missing BindingFlags causes null method = A [OK]
- Not using BindingFlags.NonPublic
- Passing null instead of empty object array to Invoke
- Assuming method must be static
Plugin and call its private method Initialize. Which sequence of reflection calls correctly bypasses compile-time safety to achieve this?Solution
Step 1: Create instance dynamically, access private method with correct BindingFlags, and invoke the private method
Activator.CreateInstance(typeof(Plugin)) creates an instance at runtime without compile-time type knowledge. GetMethod with BindingFlags.NonPublic | BindingFlags.Instance accesses the private Initialize method. Invoke calls the method on the created instance, bypassing compile-time safety.Final Answer:
Use Activator.CreateInstance(typeof(Plugin)) then GetMethod("Initialize", BindingFlags.NonPublic | BindingFlags.Instance) and invoke it -> Option BQuick Check:
Dynamic instance + private method access = C [OK]
- Calling private method without BindingFlags.NonPublic
- Using new instead of Activator for dynamic creation
- Wrong BindingFlags causing method not found
Ready to prove it?
Pass the test and this pattern moves unknown
