Dynamically Create Instance of a Type on Run Time Using Reflection in C#
Reflection is the process of describing the metadata of types, methods and fields in a code. It helps to get information about loaded assemblies and elements within it like classes, methods etc. According to microsoft documentation, Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them.
While creating test automation framework, we will come across scenarios where we need to create instance of an objects on run time, need to examine and instantiate types in an assembly, access attributes etc. One of the common usecase is when we create a generic framework, which will allow users to specify class name in feature files and handle it without doing any further modification. Let us look at how we can achieve those.
Examples of Reflection
How to get Type of an object
1 2 3 4 |
|
This will print System.String
How to get Details loaded assembly
1 2 3 |
|
This will print System.Private.CoreLib, Version=4.0.0.0, Culture=neutral
How to create instance of a Class
Creating an instance of inbuilt class can be done like below.
1 2 |
|
Creating an instance of custom class is a multistep process
1 2 3 4 5 6 7 |
|
Activator.CreateInstance has detailed explanation of various constructors here
How to call a method from created instance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Seeing this in an example will help to make our understanding clear.
- Create SimpleCalculatorClass as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
- Use reflection to create an instance of above calculator class
We will start with creating a class Handle by passing full name of teh class. Then we get details of Add method. Then we call Add method by passing parameters as an object array. It will return the value as defined in the class
1 2 3 4 5 6 7 8 9 10 11 |
|