Introduction
In this article, I’ll discuss about C# Reflection with an example. Here we’ll learn the way of getting type information using different ways and use of properties and methods of C# Reflection type class. Advanced Reflection topics like dynamically loading an assembly and late binding will also be discussed in this article. To complete the tutorial we have implemented a C# dictionary.
What is Reflection in C#?
Reflection provides objects (of type Type) that describe assemblies, modules and types. We 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 we use attributes in our code, reflection enables us to access them. Here's a simple example of reflection using the static method GetType - inherited by all types from the Object base class - to obtain the type of a variable.
// Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);
Output
System.Int32
The following example uses reflection to obtain the full name of the loaded assembly.
// Using Reflection to get information from an Assembly:
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);
Output
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Real time implementation of Reflection
Firstly, we will create a C# console application and add two classes named Student.cs and StudentFunction.cs. The Student.cs class contains some properties of Student and the StudentFunction.cs class contains methods returning different properties value.
Student.cs class
public class Student
{
public string Name { get; set; }
public string University { get; set; }
public int Roll { get; set; }
}
StudentFunction.cs class
class StudentFunction
{
private Student student;
public StudentFunction()
{
student = new Student
{
Name = "Gopal C. Bala",
University = "Jahangirnagar University",
Roll = 1424
};
}
public string GetName()
{
return student.Name;
}
public string GetUniversity()
{
return student.University;
}
public int GetRoll()
{
return student.Roll;
}
}
Our goal is to dynamically create an instance of StudentFunction and get values from GetName(), GetUniversity() and GetRoll() method at the compile time.


Join the conversation! Your thoughts help the community grow.