Reflection
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Reflection—in object-oriented language—allows programmatic inspection of a class to find out all the information about it. In C#, reflection allows you to look inside an assembly, including all the object types contained within it. The reflection objects can be found in System.Reflection namespace.
Contents |
Example
Reflection is a very powerful tool, take for example the following scenario:
You want to print to a textbox some information about a person, but the type of information stored is expected to change very soon...
This type of situation is extremely common for a programmer working in a real-life situation where the application is developing as it travels round the development cycle. The information we know we want to store is:
- Name
- Age
- Sex
- SpecialInfomation
Base Code
using System.Reflection; Person m_PersonA = new Person(); public struct Person { public String Name; public Byte Age; public String Sex; public String SpecialInfomation; } private void Form1_Load(object sender, EventArgs e) { m_PersonA.Name = "Bill"; m_PersonA.Age = 24; m_PersonA.Sex = "Male"; m_PersonA.SpecialInfomation = "Not much really"; }
Hardcoded
You may be tempted to hard code the information which is stored knowing full well that you will later have to change it.
private void button1_Click(object sender, EventArgs e) { StringBuilder non_reflectedText = new StringBuilder(); non_reflectedText.Append(String.Format("Name: {0}\r\n",m_PersonA.Name)); non_reflectedText.Append(String.Format("Age: {0}\r\n", m_PersonA.Age)); non_reflectedText.Append(String.Format("Sex: {0}\r\n", m_PersonA.Sex)); non_reflectedText.Append(String.Format("SpecialInfomation: {0}\r\n", m_PersonA.SpecialInfomation)); textBox1.AppendText(non_reflectedText.ToString()); }
Dynamic
But let’s not make work for ourselves, instead let’s get the VES (Virtual Execution System) when running the code, find out what information is stored.
private void button1_Click(object sender, EventArgs e) { StringBuilder reflectedText = new StringBuilder(); Type programDataType = m_PersonA.GetType(); foreach (FieldInfo member in programDataType.GetFields()) { reflectedText.Append(String.Format("{0}: {1}\r\n", member.Name,member.GetValue(m_PersonA))); } textBox1.AppendText(reflectedText.ToString()); }
Output
Now when the struct is updated to hold new or different information the dynamic code will automatically show the new members of the struct along with the data.
