Reflection introduction
However, to get you started and hopefully interested, here is a small example. It solves a question that I have seen from many newcomers to any programming language: How can I change the value of a variable during runtime, only by knowing its name? Have a look at this small demo application for a solution, and read the next chapters for an explanation of the different techniques used.
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ReflectionTest { class Program { private static int a = 5, b = 10, c = 20; static void Main(string[] args) { Console.WriteLine("a + b + c = " + (a + b + c)); Console.WriteLine("Please enter the name of the variable that you wish to change:"); string varName = Console.ReadLine(); Type t = typeof(Program); FieldInfo fieldInfo = t.GetField(varName, BindingFlags.NonPublic | BindingFlags.Static); if(fieldInfo != null) { Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(null) + ". You may enter a new value now:"); string newValue = Console.ReadLine(); int newInt; if(int.TryParse(newValue, out newInt)) { fieldInfo.SetValue(null, newInt); Console.WriteLine("a + b + c = " + (a + b + c)); } Console.ReadKey(); } } } }Try running the code and see how it works. Besides the lines where we use the actual Reflection, it's all very simple. Now, go to the next chapter for some more theory on how it works.
Having problems with this chapter? Ask in our forums!
© net-tutorials.com 2006 - 2010