Reflection in C#
In this article we will learn about Reflection in C#.
Introduction
The concept of reflection is very simple in C#. Reflection is a process to collecting the information present its assembly. Reflection is a way by which a program is extracting the metadata from its assembly. A program reflect itself when It is used metadata to modify its own behavior. It is used the following namespace
Namespace :- System.Reflection
Following are the main classes defined in the System.Reflection namespace
Assembly |
Description |
EventInfo |
This class holds information for a given event. |
FieldInfo |
This class holds information for a given field. |
MemberInfo |
Class is the abstract base class for classes used to obtain information about all members of a class |
MethodInfo |
This class contains information for a given method. |
ConstructorInfo |
This class contains information for a given constructor. |
If you are using attributes in your Program, Reflection enables you to access them. You can learn about attributes in my previous article Attributes In C#
Reflection is used for performing following task
Viewing metadata
Performing type discovery
- Late binding to methods and properties
Example
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectionExample
{
class Program
{
private static int x = 5, y = 10;
static void Main(string[] args)
{
Console.WriteLine("x + y = " + (x + y));
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("x + y = " + (x + y));
}
Console.ReadLine();
}
}
}
}
The output of following program
Please enter the name of the variable that you wish to change. The variable is x in this example.
The value of x is 40.