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

How reflection bypasses compile-time safety in C Sharp (C#) - Try It Yourself

Choose your learning style9 modes available
How reflection bypasses compile-time safety
📖 Scenario: Imagine you have a simple class with a private field. Normally, you cannot access this private field directly because the compiler protects it. But using reflection, you can peek inside and change it, even though the compiler says you shouldn't.
🎯 Goal: You will create a class with a private field, then use reflection to access and modify that private field. This shows how reflection can bypass compile-time safety checks.
📋 What You'll Learn
Create a class called Person with a private string field name set to "Alice"
Create an instance of Person called person
Use reflection to get the private field name from person
Change the value of name to "Bob" using reflection
Print the value of the private field name after modification
💡 Why This Matters
🌍 Real World
Reflection is used in many tools and frameworks to inspect and modify objects at runtime, such as serializers, dependency injectors, and testing tools.
💼 Career
Understanding reflection helps developers debug, test, and extend applications dynamically, and also teaches about the limits of compile-time safety.
Progress0 / 4 steps
1
Create the Person class with a private field
Create a class called Person with a private string field name initialized to "Alice".
C Sharp (C#)
Need a hint?

Use private string name = "Alice"; inside the Person class.

2
Create an instance of Person
Create an instance of the Person class called person.
C Sharp (C#)
Need a hint?

Use Person person = new Person(); to create the object.

3
Use reflection to get the private field name
Use reflection to get the private field name from the person instance. Store it in a variable called field.
C Sharp (C#)
Need a hint?

Use typeof(Person).GetField("name", BindingFlags.NonPublic | BindingFlags.Instance) to get the private field.

4
Change the private field value and print it
Use the field variable to set the value of the private field name in person to "Bob". Then print the new value of the private field name using reflection.
C Sharp (C#)
Need a hint?

Use field.SetValue(person, "Bob") to change the value and Console.WriteLine(field.GetValue(person)) to print it.