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

How reflection bypasses compile-time safety in C Sharp (C#) - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - How reflection bypasses compile-time safety
Write code with reflection
↓
Compile-time checks skipped
↓
Run-time reflection calls
↓
Access private members or invoke methods
↓
Possible runtime errors if misuse
↓
Program continues or crashes
Reflection lets code inspect and use types at runtime, skipping compile-time safety checks, which can cause runtime errors if used incorrectly.
Execution Sample
C Sharp (C#)
using System;
using System.Reflection;

class Person {
  private string secret = "hidden";
}

class Program {
  static void Main() {
    var p = new Person();
    var secretField = typeof(Person).GetField("secret", BindingFlags.NonPublic | BindingFlags.Instance);
    var value = secretField.GetValue(p);
    Console.WriteLine(value);
  }
}
This code uses reflection to access a private field 'secret' of a Person object and prints its value, bypassing compile-time access restrictions.
Execution Table
StepActionEvaluationResult
1Create Person instance pp is new Person()p created
2Get FieldInfo for 'secret'typeof(Person).GetField("secret", BindingFlags.NonPublic | BindingFlags.Instance)FieldInfo for 'secret' found
3Get value of 'secret' from psecretField.GetValue(p)"hidden"
4Print valueConsole.WriteLine(value)Output: hidden
5EndNo more codeProgram ends
💡 Program ends after printing the private field value, showing reflection bypassed compile-time access rules.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
pnullPerson instancePerson instancePerson instancePerson instance
secretFieldnullnullFieldInfo for 'secret'FieldInfo for 'secret'FieldInfo for 'secret'
valuenullnullnull"hidden""hidden"
Key Moments - 2 Insights
Why can we access a private field 'secret' even though it's private?
Reflection ignores compile-time access modifiers, so at runtime it can access private members, as shown in step 3 of the execution_table.
What happens if the field name is misspelled in GetField?
GetField returns null, so calling GetValue on null causes a runtime error, unlike compile-time errors, shown by missing FieldInfo in step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'value' after step 3?
AFieldInfo object
Bnull
C"hidden"
DPerson instance
💡 Hint
Check the 'value' variable in variable_tracker after step 3.
At which step does reflection bypass compile-time safety to access private data?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
See execution_table step 3 where GetValue accesses the private field.
If the field name was wrong, what would happen at step 2?
AProgram prints null
BFieldInfo would be null, causing runtime error later
CCompile-time error
DProgram crashes immediately
💡 Hint
Reflection returns null if field not found, no compile-time error (see key_moments).
Concept Snapshot
Reflection lets you access and modify private members at runtime.
It skips compile-time safety checks.
Use BindingFlags to access non-public members.
Misuse can cause runtime errors.
Always check for null when using reflection.
Full Transcript
This example shows how reflection in C# can access private fields of a class at runtime, bypassing compile-time safety checks. The code creates a Person object, then uses reflection to get the private field 'secret'. It retrieves the value and prints it. The execution table traces each step: creating the object, getting the field info, reading the value, and printing it. Variables change as expected, with 'value' holding the private string after step 3. Key moments clarify why private access is possible and what happens if the field name is wrong. The quiz tests understanding of variable values and reflection behavior. Reflection is powerful but can cause runtime errors if used carelessly.

Practice

(1/5)
1. What does reflection in C# allow a program to do that bypasses compile-time safety?
easy
A. Generate compile-time warnings for unsafe code
B. Automatically optimize code for better performance
C. Inspect and modify types and members at runtime, ignoring compile-time checks
D. Prevent runtime errors by enforcing strict type checks

Solution

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

    Inspect and modify types and members at runtime, ignoring compile-time checks -> Option C
  3. Quick Check:

    Reflection bypasses compile-time safety = D [OK]
Hint: Reflection works at runtime, ignoring compile-time checks [OK]
Common Mistakes:
  • Thinking reflection improves compile-time safety
  • Confusing reflection with compile-time code generation
  • Assuming reflection prevents runtime errors
2. Which of the following C# code snippets correctly uses reflection to get the name of a private field called _secret from a class MyClass?
easy
A. var field = typeof(MyClass).GetMethod("_secret", BindingFlags.NonPublic);
B. var field = typeof(MyClass).GetField("_secret");
C. var field = typeof(MyClass).GetProperty("_secret", BindingFlags.Public);
D. var field = typeof(MyClass).GetField("_secret", BindingFlags.NonPublic | BindingFlags.Instance);

Solution

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

    var field = typeof(MyClass).GetField("_secret", BindingFlags.NonPublic | BindingFlags.Instance); -> Option D
  3. Quick Check:

    Correct BindingFlags for private field = A [OK]
Hint: Use BindingFlags.NonPublic | BindingFlags.Instance for private fields [OK]
Common Mistakes:
  • Omitting BindingFlags causing null result
  • Using GetProperty instead of GetField
  • Using BindingFlags.Public for private members
3. Consider this C# code snippet using reflection:
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?
medium
A. 40
B. 30
C. Compilation error
D. Runtime exception

Solution

  1. 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 field age. The field value is set to 40, then retrieved and printed, so output is 40.
  2. Final Answer:

    40 -> Option A
  3. Quick Check:

    Reflection sets private field value = 40 [OK]
Hint: Reflection can change private fields at runtime [OK]
Common Mistakes:
  • Assuming private fields cannot be changed
  • Expecting compile-time error
  • Thinking output remains original value
4. This code attempts to use reflection to invoke a private method 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);
medium
A. GetMethod returns null because it needs BindingFlags.NonPublic; fix by adding BindingFlags.NonPublic | BindingFlags.Instance
B. Invoke requires parameters array; fix by passing new object[] { }
C. Calculator class must be public; fix by making class public
D. Calculate method must be static; fix by declaring static

Solution

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

    GetMethod returns null because it needs BindingFlags.NonPublic; fix by adding BindingFlags.NonPublic | BindingFlags.Instance -> Option A
  3. Quick Check:

    Missing BindingFlags causes null method = A [OK]
Hint: Add BindingFlags.NonPublic to access private methods [OK]
Common Mistakes:
  • Not using BindingFlags.NonPublic
  • Passing null instead of empty object array to Invoke
  • Assuming method must be static
5. You want to use reflection to dynamically create an instance of a class named Plugin and call its private method Initialize. Which sequence of reflection calls correctly bypasses compile-time safety to achieve this?
hard
A. Use typeof(Plugin).GetConstructor(null).Invoke(null) then GetMethod("Initialize") without BindingFlags
B. Use Activator.CreateInstance(typeof(Plugin)) then GetMethod("Initialize", BindingFlags.NonPublic | BindingFlags.Instance) and invoke it
C. Use new Plugin() then call Initialize() directly
D. Use Activator.CreateInstance("Plugin") then GetMethod("Initialize", BindingFlags.Public)

Solution

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

    Use Activator.CreateInstance(typeof(Plugin)) then GetMethod("Initialize", BindingFlags.NonPublic | BindingFlags.Instance) and invoke it -> Option B
  3. Quick Check:

    Dynamic instance + private method access = C [OK]
Hint: Use Activator + BindingFlags.NonPublic to call private methods [OK]
Common Mistakes:
  • Calling private method without BindingFlags.NonPublic
  • Using new instead of Activator for dynamic creation
  • Wrong BindingFlags causing method not found
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