O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Advanced Uses of Reflection

The preceding example demonstrates the use of reflection, but doesn’t perform any tasks you can’t accomplish using normal C# language constructs. However, reflection can also manipulate types in ways not supported directly in C#, as demonstrated in this section.

While the CLR enforces access controls on type members (specified using access modifiers such as private and protected), these restrictions don’t apply to reflection. Assuming you have the correct set of permissions, you can use reflection to access and manipulate private data and function members, as this example using the Greeting subtypes from the previous section shows (see the source comment for filename and compilation information):

// InControl.cs - compile with /r:Greeting.dll,English.dll using System; using System.Reflection; class TestReflection { // Note: This method requires the ReflectionPermission perm. static void ModifyPrivateData(object o, string msg) { // Get a FieldInfo type for the private data member Type t = o.GetType(); FieldInfo fi = t.GetField("msg", BindingFlags.NonPublic| BindingFlags.Instance); // Use the FieldInfo to adjust the data member value fi.SetValue(o, msg); } static void Main() { // Create instances of both types BritishGreeting bg = new BritishGreeting(); AmericanGreeting ag = new AmericanGreeting(); // Adjust the private data via reflection ModifyPrivateData(ag, "Things are not the way they seem"); ModifyPrivateData(bg, "The runtime is in total control!"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required