Reflection in C#
In this article, I’m trying to explain the concept of reflection.
Reflection allows a C# program to inspect and manipulate itself. It can be used to effectively find all the types in an assembly and dynamically invoke methods in an assembly. It can at times even be used to emit intermediate language code on the fly so that the generated code can be executed directly.
Reflection is also used to obtain information about a class and its members. Reflection can be used to manipulate other objects on the .Net platform.
Reflection uses the System.Reflection namespace, with the type class to identity the Type of the class being reflected, and fields of a struct or enum represented by the the FieldInfo class, Members of the reflected class represented by the MemberInfo class. Methods of a reflected class represented by the MethodInfo class, and parameters to Methods represented by the ParameterInfo class.
Reflection can be used in three different ways:
- Obtaining Class and Type Information from an assembly.
- Obtaining Member Information from a Class.
- Dynamically Invoking Methods from Classes in an Assembly.
Type the below code in notepad and save as testingReflection.cs
Console.WriteLine("Invoking Program Class");
public void execute(string data)
public void compute(int p1, int p2)
Open the Visual Studio Command Prompt and type the following command:
csc /t:library testingReflection.cs
This command create a dll file named testingRelection.dll
Now open again notepad, type the following lines and save as ReflectTypes.cs in the same folder where you have saved testingReflection.cs file.
static void Main(string args)
Assembly assembly = Assembly.LoadFrom(args);
Type typearray = assembly.GetTypes();
foreach (Type type in typearray)
Console.WriteLine("Type Name : " + type.FullName);
Console.WriteLine("Type Namespace : " + type.Namespace);
Type the following command in Visual Studio Command Prompt
This command compile the file RelectTypes.cs and create ReflectTypes.exe
Run the ReflectTypes.exe with one command line argument
Execute this command and you will get the desired output.