TOC

The community is working on translating this tutorial into Polish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Reflection:

Reflection introduction

Wikipedia says that "In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour". This is exactly how Reflection in C# works, and while you may not realize it at this point, being able to examine and change information about your application during runtime, offers huge potential. Reflection, which is both a general term, as well as the actual name of the reflection capabilities in C#, works very, very well, and it's actually not that hard to use. In the next couple of chapters, we will go more into depth about how it works and provide you with some cool examples, which should show you just how useful Reflection is.

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.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!