Reflection in C# is a method to provide objects with assembly, module, and type information that can be used at run-time to bind and create instances within the application.
The System.Reflection
namespace must be defined to include and manipulate objects at run-time dynamically. It has multiple methods to perform reflection-related tasks.
The following are the reflection methods:
1. typeof(arg);2. GetType();
The typeof()
function is used to get the type of an object/variable at compile time. This can be used to instantiate objects of System.Type
. It takes the data type as the parameter whose type we want to know.
The GetType()
function is used to return an instance of Type
class which can further be used for reflection. It does not have any arguments.
The following code snippets help us to understand the concept of reflection better:
using System;using System.Reflection;class Program{static void Main(){char variable = 'H';//GetType() method to return the type of the varibleConsole.WriteLine(variable.GetType());}}
As seen from the output, the return value of the GetType()
function returns the variable
that has a type of System.Char
, which is true because we initiated the variable
with a character in the program.
We can dynamically instantiate an object by using the typeof()
function:
using System;using System.Reflection;class Program{static void Main(){int variable = (int)Activator.CreateInstance(typeof(int));Console.WriteLine(variable);Console.WriteLine(variable.GetType());//uncomment this to understand that typeof() works//only on data types//Console.WriteLine(typeof(variable));}}
Line 7: We use the typeof()
function to create an instance of an integer type. The Activator
class is a system class that is responsible for creating objects. The CreateInstance()
function of the Activator
class creates an integer instance with the name variable
.
Line 8: We display the initial value of the variable
after it has been instantiated.
Line 9: We display the type information of the variable using the GetType()
function.
Line 12: This code line will throw an error if we uncomment and execute it. This is because the typeof()
function needs a data type as its parameter.
Following are some of the common uses of reflection in C#:
It is used for the dynamic binding of data types at run-time.
We can access information on modules, including all global and non-global methods.
We can access information on namespace methods, parameters, and other details.
Free Resources